#!/bin/sh

dotfilebase="/tmp/.princess"

me=`whoami`
portfile="$dotfilebase"_"$me"

if [ $(uname) = "Linux" ]; then
    pathCmd="readlink -f"
elif [ $(uname) = "Darwin" ]; then
    pathCmd="stat -f %N"
else
    pathCmd="realpath"
fi

################################################################################

startDaemon() {
    lockfile="$dotfilebase"_lock_"$me"

    while [ -f "$lockfile" ] && \
          [ $(( `date +%s` - `date -r "$lockfile" +%s` )) -le 10 ]; do
        # apparently a concurrent script is starting up the daemon
        # already
        echo "waiting ..."
        sleep 1
    done
        
    if [ ! -f "$portfile" ]; then
        touch "$lockfile"

        BASEDIR=`dirname $($pathCmd $0)`

        export CLASSPATH=$CLASSPATH:$BASEDIR/dist/princess-all.jar

        tempportfile=`mktemp`
        touch "$tempportfile"
        chmod go-rwx "$tempportfile"

        java -Xss20000k -Xmx1500m -noverify ap.ServerMain >"$tempportfile" &

        sleep 1
        while [ `wc -l "$tempportfile" | gawk '{ printf $1 }'` -lt 2 ]; do
            sleep 1
        done

        mv "$tempportfile" "$portfile"
        rm "$lockfile"
    fi
}

################################################################################

if [ ! -f "$portfile" ]; then
    startDaemon
fi

mainProcess=$$

success=1
until [ $success -eq 0 ]; do

    port=`head -n1 "$portfile"`

    (
        # send the ticket
        tail -n1 "$portfile"

        # command line arguments
        for var; do
	    case "$var" in
		-*|+*)
		    echo "$var"
		    ;;
		*)
		    echo `$pathCmd "$var"`
		    ;;
	    esac
        done

        echo "PROVE_AND_EXIT"

        # ping the daemon every second, to show that we are still
        # alive
        {
            sleep 1
            while ps -p $mainProcess >/dev/null; do
                echo "PING"
                sleep 1
            done
        } &
    ) | nc localhost $port

    success=$?

    if [ $success -ne 0 ]; then
        rm "$portfile"
        startDaemon
    fi

done
