#!/usr/bin/env bash

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_NETWORKDISCOVERY`
if test -z "$JVM_OPTS"; then
  JVM_OPTS="-Xmx256m"
fi
JVM_OPTS="$JVM_OPTS -Djava.ext.dirs=${javalibdir}"

CUR_DIR=${javalibdir}/networkDiscovery
LOG_DIR="${localstatedir}/log/networkDiscovery"
OUTLOG=${LOG_DIR}/networkDiscovery-$1.html
ERRLOG=${LOG_DIR}/networkDiscovery-stderr.log

# If error log exists and has content, we rename it before creating a
# new one
if test -s ${ERRLOG}; then
    newname="${ERRLOG}.`date +'%Y-%m-%d-%H%M'`.log"
    mv ${ERRLOG} ${newname}
fi

cd $CUR_DIR
# Run program
$JAVA $JVM_OPTS -jar networkDiscovery.jar $* > ${OUTLOG} 2> ${ERRLOG}
