#!/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)`
        EXTLIBSDIR=$BASEDIR/extlibs
        ASSEMBLY=$BASEDIR/target/scala-2.*/Princess-assembly*

        export JAVA_OPTS="-Xss20000k -Xmx1500m"

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

        if [ -f $ASSEMBLY ]; then
            java $JAVA_OPTS -cp $ASSEMBLY ap.ServerMain >"$tempportfile" &
        else
            export CLASSPATH=$CLASSPATH:$BASEDIR/bin:$BASEDIR/smt-parser/smt-parser.jar:$BASEDIR/parser/parser.jar:$EXTLIBSDIR/java-cup-11a.jar
            scala ap.ServerMain >"$tempportfile" &
        fi

        sleep 1
        while [ `wc -l "$tempportfile" | awk '{ 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
