#!/bin/bash

set -e

#PATH="/var/lib/gforge/chroot/home/users/evaso-guest/projects/dehs:$PATH"
export BASEDIR=/org/home/groups/dehs
export WORKDIR=$BASEDIR/dehs_prj/dehs
LOCK=$BASEDIR/run.lock
BNAME=$(basename "$0")

attempts=0
maxattempts=30

while true; do
    if [ -e $LOCK ]; then
        PID=$(cat $LOCK)
        if [ ! -n "$PID" ] || ! ps -p "$PID" | grep "$BNAME" &>/dev/null; then
            echo "Removing stale lock file"
            rm $LOCK
        else
            if [ $attempts -eq $maxattempts ]; then
                echo "Max number of attempts ($maxattempts) to run reached, surrending to a forever running instance" >&2
                exit 1
            fi
            # lock file is okay, dehs.sh running
            # let's wait ten minutes and try again
            sleep $((10 * 60)) || exit 1
            attempts=$(($attempts + 1))
        fi
    else
        break
    fi
done

echo $$ > $LOCK

run_type="-update_all"

if [ ! -z "$1" ]; then
    case $1 in
        all)
                run_type="-update_all"
        ;;
        new)
                run_type="-update_new"
        ;;
        bogus)
                run_type="-update_bogus"
        ;;
        wwiz)
                run_type="-wwiz"
        ;;
        *)
                echo "Unknown run-type: $1" >&2
                exit 1
        ;;
    esac
fi

#(cd /tmp/; svn export svn://svn/devscripts/trunk/scripts/uscan.pl && mv uscan.pl $WORKDIR/) || true
cd /tmp/
if svn export svn://svn/devscripts/trunk/scripts/uscan.pl 1>/dev/null; then
	sed -i "s/###VERSION###/DEHS-SVN/g" uscan.pl
	if ! diff $WORKDIR/uscan.pl ./uscan.pl; then
		echo "New uscan.pl available" >&2
	fi
	rm -f uscan.pl
fi

$WORKDIR/dehs_pg.php $run_type 2>$WORKDIR/logs/stderr.log 1>$WORKDIR/logs/stdout.log
$WORKDIR/update_wwwal.sh &>/dev/null

rm $LOCK
