#!/bin/sh

if [ $# -le 1 ]
then
  echo "Usage: `basename $0` phpfreechat_path checkmd5_output_filename"
  echo "exempel: `basename $0` ~/pfc/misc/phpfreechat ~/pfc/misc/phpfreechat/checkmd5.php"
  exit;
fi

PFC_PATH=$1
DST=$2
TMP=/tmp/checkmd5.php

if ( test -f $DST )
then
  echo "$DST should not exist. Please delete this file."
  exit;
fi

if ( test ! -f $PFC_PATH/version.txt  )
then
  echo "$PFC_PATH/version.txt doesn't exist."
  exit;
fi
    
echo "--> Creating $DST"

cd $PFC_PATH
echo "<?php" > $TMP
echo '$files_ok = array();' >> $TMP
echo '$files_ko = array();' >> $TMP
for f in `find . -type f`
do
  if ( test $f != "./index.php"  )
  then
    sum=`md5sum $f | sed "s/\s.*$//g"`
    echo 'if (md5(file_get_contents("'$f'")) == "'$sum'")' >> $TMP
    echo '  $files_ok[] = "<span style=\"color:#3A3\">ok - '$f'</span>\n";' >> $TMP
    echo 'else' >> $TMP
    echo '  $files_ko[] = "<span style=\"color:#F33\">corrupted - '$f' (please replace this file by a correct one)</span>\n";' >> $TMP
  fi
done

echo 'echo "<h2>Checking phpfreechat files validity</h2>";' >> $TMP
echo 'echo "<pre>\n";' >> $TMP
echo '$arr = array_merge($files_ko,$files_ok);' >> $TMP
echo 'foreach($arr as $file)' >> $TMP
echo '  echo $file;' >> $TMP
echo 'echo "</pre>\n";' >> $TMP
echo "?>" >> $TMP
cd - >/dev/null

cp $TMP $DST

echo "---> Done, $DST created"
