#!/bin/bash
echo "Test Database"
WWW_HOME=/home/aandt/www
ZIPFILE="/home/aandt/www/uploads/ATProcessor.zip"
LOGFILE="/home/aandt/www/logs/upgrade.log"

sqlite3 $WWW_HOME/configDB.db "PRAGMA quick_check" | grep 'ok' &> /dev/null
if [ $? == 0 ]; then
        echo "OK"
        cp $WWW_HOME/configDB.db $WWW_HOME/configDB.backup
else
        echo "Not Ok"
        cp $WWW_HOME/configDB.backup $WWW_HOME/configDB.db
		chmod a+rw $WWW_HOME/configDB.db
fi


echo  "Upgrading"

mv $WWW_HOME/uploads/ATProcessor*.zip $WWW_HOME/uploads/ATProcessor.zip &> /dev/null

if [ -f "$ZIPFILE" ]
then
	echo "File Exists Upgrading" >> $LOGFILE
	date >> $LOGFILE
	rm -r /tmp/www/
	rm -r /tmp/ATProc
	unzip $ZIPFILE -d /tmp
	cp /tmp/ATProc/ATProcessor /home/aandt/ATProc
	cp /tmp/ATProc/*.sh /home/aandt/ATProc
	cp -r /tmp/www/* /home/aandt/www
	rm -f $ZIPFILE
else
	echo "Upgrade File not Found"
fi

# run a patch file if found
PATCHFILE="/home/aandt/ATProc/patch.sh"
if [ -f "$PATCHFILE" ]
then
	echo "Patch File Exists Running" >> $LOGFILE
	date >> $LOGFILE
	chmod a+x $PATCHFILE
	$PATCHFILE
	rm -f $PATCHFILE
else
	echo "Patch File Not found"
fi
