#! /bin/sh
### BEGIN INIT INFO
# chkconfig: 345 95 5
# description:      MistServer - next generation multimedia server
### END INIT INFO

NAME=MistController
DESC="MistServer"
CFG_FILE=/usr/local/bin/mist/config.json
PID_FILE=/var/run/mistserver.pid
LOG_FILE=/var/log/mistserver.log

# Source function library.
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:/usr/local/bin/mist

. /lib/lsb/init-functions

# output
#CONOUTPUT="/dev/null"
CONOUTPUT=$LOG_FILE

#
# Function that starts the daemon/service
#
do_start()
{
  cd /usr/local/bin/mist
  printf '%s\n'"Working from folder: ""$( pwd)"
  printf '%s\n' "Starting $DESC" "$NAME"
  MistController > $CONOUTPUT 2>&1 &
  printf '%s\n' "Started server. Output redirected to ${CONOUTPUT}."
  printf '%s\n' ""
}

#
# Function that stops the daemon/service
#
do_stop()
{
  printf '%s\n' "Stopping $DESC" "$NAME"
  killall MistController -s SIGTERM
  printf '%s\n' "Execution submitted."
  printf '%s\n' ""
}

do_restart()
{
  printf '%s\n' "Restarting $DESC" "$NAME"
  [[ -f /var/lock/$NAME ]] && killall SIGKILL MistController -s SIGTERM > $CONOUTPUT 2>&1 && rm -f /var/lock/$NAME $PID_FILE && sleep 2
  cd /usr/local/bin/mist
  MistController > $CONOUTPUT 2>&1 &
  printf '%s\n' "Kill and restart initiated."
  printf '%s\n' ""
}

case "$1" in
  start)
    do_start
    ;;
  stop)
    do_stop
    ;;
  restart)
    do_restart
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
    exit 3
    ;;
esac
exit 0
