#!/usr/bin/env bash

APP_USER=root
APP_NAME=powerapid
COMMONS_DAEMON_JAR_LOCATION=/usr/share/java
COMMONS_DAEMON_JAR_NAME=commons-daemon-1.0.15.jar
COMMONS_DAEMON_JAR_FULL_PATH=$COMMONS_DAEMON_JAR_LOCATION/$COMMONS_DAEMON_JAR_NAME
STARTUP_DELAY=20

if [ -z "${JAVA_HOME}" ]; then
        JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:/bin/java::")
fi

DAEMON=/usr/bin/jsvc

TMP_DIR=/tmp
PID_FILE=/var/run/jsvc-$APP_NAME.pid

#CLASSPATH=$COMMONS_DAEMON_JAR_FULL_PATH:$APP_BASE_DIR/$APP_NAME.jar

realpath () {
(
  TARGET_FILE="$1"
  CHECK_CYGWIN="$2"

  cd "$(dirname "$TARGET_FILE")"
  TARGET_FILE=$(basename "$TARGET_FILE")

  COUNT=0
  while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ]
  do
      TARGET_FILE=$(readlink "$TARGET_FILE")
      cd "$(dirname "$TARGET_FILE")"
      TARGET_FILE=$(basename "$TARGET_FILE")
      COUNT=$(($COUNT + 1))
  done

  if [ "$TARGET_FILE" == "." -o "$TARGET_FILE" == ".." ]; then
    cd "$TARGET_FILE"
    TARGET_FILEPATH=
  else
    TARGET_FILEPATH=/$TARGET_FILE
  fi

  # make sure we grab the actual windows path, instead of cygwin's path.
  if [[ "x$CHECK_CYGWIN" == "x" ]]; then
    echo "$(pwd -P)/$TARGET_FILE"
  else
    echo $(cygwinpath "$(pwd -P)/$TARGET_FILE")
  fi
)
}

start() {
    declare -r real_script_path="$(realpath "$0")"
    declare -r app_home="$(realpath "$(dirname "$real_script_path")")"
    declare -r lib_dir="$(realpath "${app_home}/../lib")"
    ${{template_declares}}
    #declare -r script_conf_file="${app_home}/../conf/application.ini"
    #declare -r app_classpath="$COMMONS_DAEMON_JAR_FULL_PATH:$lib_dir/../lib:$lib_dir/../conf:$lib_dir/../scripts"

    echo "Starting $APP_NAME as a daemon..."

    $DAEMON \
    -pidfile $PID_FILE \
    -procname $APP_NAME \
    -user $APP_USER \
    -home $JAVA_HOME \
    -Djava.io.tmpdir=$TMP_DIR \
    -outfile /var/log/$APP_NAME \
    -errfile '&1' \
    -wait $STARTUP_DELAY \
    -cp $app_classpath \
    $app_mainclass
    # To get a verbose JVM
    #-verbose \
    # To get a debug of jsvc.
    #-debug \
}

stop() {
    echo "Stopping $APP_NAME..."

    $DAEMON \
    -stop \
    -pidfile $PID_FILE \
    org.powerapi.daemon.PowerAPId
}

status() {
    local PID="null"
    if [ -s $PID_FILE ]; then
        PID=$(cat $PID_FILE)
    fi

    if [ -d /proc/$PID ]; then
        echo "- $APP_NAME is running [$PID]"
    else
        echo "- $APP_NAME is NOT running"
    fi
}

case "$1" in
    start)
        start $app_classpath
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0  { start | stop | restart | status }"
        exit 1
esac

exit 0
