#!/bin/sh

echo ""
echo " --- KSPS-0612 Kommunikationsrechner ---"
echo " Running installation for web-interface"
echo " ... please wait"
echo ""

INSTALLDIR=/
TMPDIR=/tmp/web/

SKIP=`awk '/^__ARCHIVE_FOLLOWS__/ { print NR + 1; exit 0; }' $0`

rm -R ${TMPDIR}*
mkdir -p $TMPDIR

# Take the TGZ portion of this file and pipe it to tar
tail +$SKIP $0 | tar xzv -C $TMPDIR

# check return code
RC=$?
if [ $RC -ne 0 ]; then
  echo "Unable to untar the archive (return code: " $RC ")"
  exit $RC
fi

# check for enough disk space
DISKSPACE=`df $INSTALLDIR | awk 'NR == 2 {print $2}'` 
USED_DISKSPACE=`du -s $INSTALLDIR | awk '{print $1}'`
if [ -d ${INSTALLDIR}httpd ]; then
	USED_BY_HTTPD=`du -s ${INSTALLDIR}httpd | awk '{print $1}'`
else
	USED_BY_HTTPD=0;
fi
NEW_HTTPD_SIZE=`du -s ${TMPDIR}httpd | awk '{print $1}'`

((FREE_SPACE=DISKSPACE-USED_DISKSPACE+USED_BY_HTTPD))

if (( FREE_SPACE < NEWHTTPD_SIZE )); then
  echo "no space left on device"
  exit 28 # no space left on device
fi

# stop running processes so they can be removed or replaced
killall webservereventhandler

# remove old files
rm -R ${INSTALLDIR}httpd

# remove moved files
rm -R ${INSTALLDIR}etc/webservereventhandler

#copy new files
cp -R ${TMPDIR}* $INSTALLDIR

# create html directory
mkdir -p ${INSTALLDIR}httpd/html/
#ln -s /tmp ${INSTALLDIR}httpd/html/tmp/


echo ""
echo " Installation has been finished."
echo ""

exit 0

__ARCHIVE_FOLLOWS__
