#!/bin/sh
#
### BEGIN INIT INFO
# Provides: repose-valve
# Required-Start: $network
# Required-Stop:  $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short Description: Startup script for Repose Valve
# Description: Script for starting Repose Valve as a daemon on system startup
### END INIT INFO

set -e

# Source function library.
. /lib/lsb/init-functions

# Set sensible defaults

JAVA=/usr/bin/java
CONFIG_DIRECTORY=/etc/repose
USER=repose
NAME=repose-valve
DAEMON_HOME=/usr/share/repose
PID_FILE=/var/run/${NAME}.pid
REPOSE_JAR=${DAEMON_HOME}/${NAME}.jar
START_ARGS="--start --quiet --oknodo --make-pidfile --pidfile ${PID_FILE} --background"
JAVA_OPTS=""
RUN_OPTS="-c $CONFIG_DIRECTORY"
CLEAN=/usr/bin/clean-repose-deploy


# Can override the defaults in /etc/sysconfig
. /etc/sysconfig/repose

# Validate that we have a java executable on the path
command -v $JAVA >/dev/null 2>&1
if [ $? -gt 0 ]; then
  echo 'Repose requires the "JAVA" environment variable be set to the absolute path of a Java executable!'
  echo " - The current value ($JAVA) is invalid."
  echo ' - This can be updated in the configuration file: /etc/sysconfig/repose'
  echo 'Exiting!'
  exit 1
fi

# We've found a java on the path, now validate that the minor version is adequate.
# We're not guaranteed to have bash on Debian flavors, so we have to use sh stuff.
VERSION=$($JAVA -version 2>&1 | grep ' version' | awk '{ print substr($3, 2, length($3)-2); }')
JAVA_MINOR=$(echo $VERSION | tr "." " " | cut -d " " -f2)

if [ "$JAVA_MINOR" -lt "8" ]; then
  echo 'Repose requires a Java version of at least 8 to function.'
  echo 'Please install a JRE 1.8 or greater.'
  exit 1
fi

###########################
# Start daemon
###########################
start_repose()
{
  $CLEAN $CONFIG_DIRECTORY
  start-stop-daemon $START_ARGS --chuid $USER:$USER --exec $JAVA -- $JAVA_OPTS -jar $REPOSE_JAR $RUN_OPTS
  log_progress_msg "started"
}

###########################
# Stop daemon
###########################
stop_repose()
{
  start-stop-daemon -p $PID_FILE --stop --user $USER --retry 5 --exec $JAVA
  log_progress_msg "stopped"
}

# -----------------------------------------------------------------------------
# Script entry point...
# -----------------------------------------------------------------------------
# Switch to the daemon's home directory to do all of this...
cd $DAEMON_HOME

if [ $? -ne 0 ]; then
  echo "Unable to find $NAME's directory."
  exit 1
fi

case "$1" in
  start)
    log_daemon_msg "Starting $NAME"
    start_repose
    log_end_msg 0
    ;;
  stop)
    log_daemon_msg "Stopping $NAME"
    stop_repose
    log_end_msg 0
    ;;
  restart)
    log_daemon_msg "Restarting $NAME"
    stop_repose
    start_repose
    log_end_msg 0
    ;;
  status)
    status_of_proc -p $PID_FILE $JAVA $NAME && exit 0 || exit $?
    ;;

  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|restart|status}"
    exit 1
esac
