#!/bin/sh
#
# Copyright by NeptuneLabs GmbH 2011
#

UNZIP_APP="unzip"

new_files() {
  ls "$1" | while IFS= read i; do
    if [ -d "$1/$i" ]; then
      if [ "$i" != "storage" ]; then
        new_files "$1/$i" "$2" "$3" "$4" "$5"
      fi
   elif [ -f "$1/$i" ]; then
     fsrc="$1/$i"
     sub=`expr substr "$fsrc" $3 10000`
     dfile="$2$sub"
     if [ ! -f "$dfile" ]; then
       echo "$sub" >> "$4"
     else
       cmp -s "$fsrc" "$dfile"
       if [ "$?" -ne "0" ]; then
         echo "$sub" >> "$5"
       fi
     fi
   fi
  done
}

unzip=`which $UNZIP_APP`
if [ "$?" -ne "0" ]; then
  echo "Sorry, cannot find required application $UNZIP_APP"
  exit 1
fi

if [ "$#" -ne "2" ]; then
  echo "Usage: $0 fsi.war current_installation_dir"
  echo
  echo "Shows differences between existing FSI Server installation and a fsi.war file"
  exit 1
else
  if [ ! -f $1 ]; then
    echo "$1 WAR file not found"
    exit 1
  fi
  if [ ! -d $2 ]; then
    echo "$2 not a fsi server installation directory"
    exit 1
  else
    if [ ! -f "$2/WEB-INF/lib/fsi.jar" ]; then
      echo "$2 is not a fsi server installation directory"
      exit 1
    fi
  fi
fi

tmpf=$(mktemp -d) || exit

$unzip -q $1 -d $tmpf

if [ ! -f "$tmpf/WEB-INF/lib/fsi.jar" ]; then
  echo "$1 is not a fsi server WAR file"
else
  newfiles=$(mktemp) || exit
  chgfiles=$(mktemp) || exit

  precount=`expr ${#tmpf} + 1`
  new_files "$tmpf" "$2" "$precount" "$newfiles" "$chgfiles"

  subfiles=$(mktemp) || exit
  delfiles=$(mktemp) || exit

  precount=`expr ${#2} + 1`
  new_files "$2" "$tmpf" "$precount" "$subfiles" "$delfiles"

  echo "New files in $1"
  echo "-------------------------------"
  cat $newfiles
  echo
  echo "Changed files in $1"
  echo "-------------------------------"
  cat $chgfiles
  echo
  echo "Deleted files in $1"
  echo "-------------------------------"
  cat $subfiles

  rm -f $newfiles $chgfiles $subfiles $delfiles
fi

rm -Rf $tmpf

