#!/bin/sh
#
# chkconfig: 2345 90 60
# description: streaming server
#
### BEGIN INIT INFO
# Provides:          flussonic
# Required-Start:    $local_fs $network
# Should-Start:      $remote_fs $syslog $time
# Required-Stop:     $local_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop flussonic streaming server
### END INIT INFO


# This script is only for launching with systemd.
# It exists for smooth migration from old SysV init scripts to new usage

export HOME=/etc/flussonic
mkdir -p $HOME
mkdir -p /var/run/flussonic
export PATH=/opt/flussonic/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin
export LANG=C

if [ -z ${ERL_INETRC+x} ]; then
  if [ -f /etc/flussonic/.inetrc ]; then
    export ERL_INETRC=/etc/flussonic/.inetrc
  elif [ -f /opt/flussonic/.inetrc ]; then
    export ERL_INETRC=/opt/flussonic/.inetrc
  else
    export ERL_INETRC=`pwd`/deploy/packaging/root/opt/flussonic/.inetrc
  fi
fi


cd /opt/flussonic


case "$1" in
"newstart")
  systemctl start flussonic
  ;;
"newstop")
  systemctl stop flussonic
  ;;
"newreload")
  systemctl reload flussonic
  ;;
"newrestart")
  systemctl restart flussonic
  ;;


"run")
  /opt/flussonic/bin/run -p /var/run/flussonic/pid -l /var/log/flussonic
  ;;


"oldstart")
  /opt/flussonic/bin/epmd -relaxed_command_check -daemon 2>/dev/null
  if ./contrib/control.erl alive ; then
    echo Streamer is running already
    exit
  fi
  echo -n "Starting flussonic: "
  export PROCNAME=flussonic
  exec /opt/flussonic/bin/run -p /var/run/flussonic/pid -b /var/run/flussonic/boot-error.txt -l /var/log/flussonic -d
  ;;
"oldstop")
  ./contrib/control.erl stop -p "/var/run/flussonic/pid"
  ;;
"oldreload")
  ./contrib/control.erl reload
  ;;
"oldrestart")
  $0 stop
  $0 start
  ;;


"start")
  if command -v systemctl >/dev/null ; then $0 newstart ; else $0 oldstart ; fi
  ;;
"stop")
  if command -v systemctl >/dev/null ; then $0 newstop ; else $0 oldstop ; fi
  ;;
"reload")
  if command -v systemctl >/dev/null ; then $0 newreload ; else $0 oldreload ; fi
  ;;
"restart")
  if command -v systemctl >/dev/null ; then $0 newrestart ; else $0 oldrestart ; fi
  ;;

"status")
  $0 runtime
  ;;
"runtime")
  ./contrib/control.erl status
  ;;
"license-clients")
  ./contrib/control.erl license_clients
  ;;
"shell")
  echo "Remote shell"
  erl -name debug$$@server.l -remsh streamer@server.l
  ;;
"upload-logs")
  echo "Uploading logs"
  ./contrib/control.erl upload
  echo -e $STATUS
  ;;
*)
  echo "$0 start|stop|run|reload|restart|shell|upload-logs"
esac

