#!/bin/sh

if ! test -f "index.php3"; then
	echo "A executer dans /var/www/Sherpath/ .."
	exit 1
fi

SHX_VERSION="`grep \"\shx_version=\" index.php|sed -e 's/.*=\\\"\(.*\)\\\".*/\1/'`"
SHX_DATE="`date +%d_%m_%Y`"
SHX_TAR="sherx_$SHX_DATE.tar.gz"
SHX_INSTTAR="SherpathUpdSsleepy_$SHX_DATE.tar.gz"

tar cvfz "/tmp/$SHX_TAR" `find ./ -regex ".*" -type f | grep -v "database/common.config.php3" | grep -v "default/common.config.php3" | grep -v "fax/templates/logo.gif" | grep -v "config/setup/" `
##tar cvfz "/tmp/$SHX_TAR" `find ./ -name "*" -type f | grep -v "database/common.config.php3" | grep -v "default/common.config.php3" | grep -v "graphics/common.config.php3" | grep -v "fax/templates/logo.gif" `

# Install script

cat > "/tmp/install" << EOF
#!/bin/sh

# Info
SOFTNAME="Sherpath $SHX_VERSION ($SHX_DATE)"
SOFTCOMMENT="Sherpath"
#

echo "installing \$SOFTNAME.. (\$SOFTCOMMENT)"

# TODO - Software install
###

SHX_REP="/var/www"
if test -d "\$SHX_REP/Sherpath"; then
	if ! test -f "\$SHX_REP/Sherpath-noupdate"; then
		if test -f "$SHX_TAR"; then
			rm -rf "\$SHX_REP/Sherpath.old" 2>/dev/null
			if cp -a "\$SHX_REP/Sherpath" "\$SHX_REP/Sherpath.old"; then
				chown -R www-data:www-data "\$SHX_REP/Sherpath.old"
				if tar xfzp "$SHX_TAR" -C "\$SHX_REP/Sherpath/"; then 
					if test -d "\$SHX_REP/Sherpath/template"; then
						cp -a "\$SHX_REP/Sherpath/template/"* "\$SHX_REP/Sherpath/"
					fi
					chown -R www-data:www-data "\$SHX_REP/Sherpath"
					find "\$SHX_REP/Sherpath/" -type f -exec chmod u=rw,g=r,o= "{}" \;
					find "\$SHX_REP/Sherpath/" -type d -exec chmod u=rwx,g=rx,o= "{}" \;
					find "\$SHX_REP/Sherpath/" -type f -name "*.php" -exec chmod u=rwx,g=rx,o= "{}" \;
					find "\$SHX_REP/Sherpath/" -type f -name .htaccess -exec chmod u=r,g=,o= "{}" \;
					chmod ug+x /var/www/Sherpath/setup/*
					echo "\`find \"\$SHX_REP/Sherpath/\" -type f|wc -l\` files in \$SHX_REP/Sherpath"
				else
					echo "Unable to detar archive, restoring old version"
					rm -rf "\$SHX_REP/Sherpath" 2>/dev/null
					mv -f "\$SHX_REP/Sherpath.old" "\$SHX_REP/Sherpath"
					exit 1
				fi
			else
				echo "Unable to make a backup copy of \$SHX_REP/Sherpath, aborting"
				rm -rf "\$SHX_REP/Sherpath.old" 2>/dev/null
				exit 1
			fi
		else
			echo "Sherpath archive not found, not upgrading.."
			exit 1
		fi
	else
		echo "Sherpath-noupdate found (in \$SHX_REP), not upgrading.."
		exit
	fi
else
	echo "Sherpath not installed in \$SHX_REP, not upgrading.."
	exit
fi

###

# Aide init

# useless here
#if ! ps -ef|grep -v grep|grep aide > /dev/null; then
#        echo "running aide --init .."
#        nohup sh -c "aide --init; cp -f /var/lib/aide/aide.db.new /var/lib/aide/aide.db" >/dev/null 2>/dev/null &
#else
#        echo "not launching aide --init (running)"
#fi

# Quit
EOF

# Build archive
cd /tmp
chmod a+rx install
tar cvfz "$SHX_INSTTAR" "install" "$SHX_TAR"

# Copy it
scp "/tmp/$SHX_INSTTAR" root@huguette:/root/ssleepy/

