#!/usr/bin/env bash
# This script is relatively complicated.  The getBoksMacs process sometimes
# hangs, and instead of fixing the bug that causes this problem, an elaborate
# hack to kill the process has been written instead.  getBoksMacs indicates
# that its work is done by creating the $JOB_FINISHED file.

prefix=/usr/local/nav
exec_prefix=${prefix}
bindir=${exec_prefix}/bin
localstatedir=${prefix}/var
sysconfdir=${prefix}/etc
libdir=${exec_prefix}/lib
javalibdir=${libdir}/java

NAV_CONF="${sysconfdir}/nav.conf"

function getopt() {
  awk -F= "/$1/"' && $1!~/#.*/{gsub("^[\t ]+", "", $2); gsub("[\t ]+$", "", $2); print $2}' $NAV_CONF
}

if test -z "$JAVA_HOME"; then 
    JAVA_HOME=`getopt JAVA_HOME`
fi

if test -z "$JAVA_HOME"; then
    JAVA=`which java`
else
    JAVA="$JAVA_HOME/bin/java"
fi

if ! test -x "$JAVA"; then
    echo "Could not find a suitable Java environment." >&2
    echo "Maybe you should set the JAVA_HOME variable?" >&2
    exit 1
fi

JVM_OPTS=`getopt JVM_OPTS_GETBOKSMACS`
if test -z "$JVM_OPTS"; then
  JVM_OPTS="-Xmx256m"
fi
JVM_OPTS="$JVM_OPTS -Djava.ext.dirs=${javalibdir}"

CUR_DIR=${javalibdir}/getBoksMacs
LOG_DIR="${localstatedir}/log"
PIDFILE=${localstatedir}/run/getBoksMacs.pid
JOB_FINISHED=${localstatedir}/run/boksmacs-finished.flag


getpid() {
    if test -f "$PIDFILE"; then
	local pidnum=`cat $PIDFILE`
	if (ps -p "${pidnum}" >/dev/null); then
	    echo $pidnum
	fi
    fi
}

if test -z `getpid` || test -f "$JOB_FINISHED"; then
    cd $CUR_DIR
    if test -f "$JOB_FINISHED"; then
        # Must kill old script
	kill -9 $pidnum
	rm -f "$JOB_FINISHED"
	sleep 2
    fi

    # Check again that getBoksMacs is not already running
    if test -z `getpid`; then
        # Now run the camlogger
	$JAVA $JVM_OPTS -jar getBoksMacs.jar $1 >> "$LOG_DIR/getBoksMacs.log" &
	pidno="$!"
	echo $pidno >$PIDFILE
	wait $pidno
	if test -f "$JOB_FINISHED"; then
	    rm -f "$JOB_FINISHED"
	fi
	rm $PIDFILE
    else
	echo "ERROR, kill -9 of previous getBoksMacs failed!" >&2
	exit 1
    fi
else
    echo "Previous instance of getBoksMacs is still not finished" >&2
fi
