#!/bin/sh
### BEGIN INIT INFO
# Provides:          stcp
# Required-Start:    $local_fs $network $time $syslog
# Required-Stop:     $local_fs $network $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Sistematics Server v3
### END INIT INFO
# Date of installation {{ ansible_date_time.date }}

BASE_DIR="{{ stcp_base_dir }}"
STCP_INSTANCE_NAME="{{ stcp_instance_name }}"
MULTISRV="$BASE_DIR/$STCP_INSTANCE_NAME/multi_srv_raw"
LOOP="$BASE_DIR/loop"
CFG="$BASE_DIR/$STCP_INSTANCE_NAME/server.ini"
STCP_PIDFILE="/var/run/stcp_${STCP_INSTANCE_NAME}.pid"
EXT_IF={{ ext_iface }}
PORT_MIN={{ server_port }}
MODE={{ stcp_mode }}
RUNAS={{ stcp_runas }}

DAEMON_PIDFILE="/var/run/stcp_${STCP_INSTANCE_NAME}_loop.pid"
DAEMON_LOGFILE="/var/log/stcp_${STCP_INSTANCE_NAME}_loop.log"

start() {
  if [ -f $DAEMON_PIDFILE ] && kill -0 $(cat $DAEMON_PIDFILE); then
    echo -e '\033[1;33m[WARN]\033[0m Service already running' >&2
    return 1
  fi
  echo -e '\033[0;34m[NOTIFY]\033[0m Starting service…' >&2
  local CMD="$LOOP $MULTISRV $CFG $STCP_PIDFILE $EXT_IF $PORT_MIN $MODE &>\"$DAEMON_LOGFILE\" & echo \$!"
  su -s /bin/sh -c "$CMD" $RUNAS > $DAEMON_PIDFILE 2>&1 &
  echo -e '\033[0;32m[OK]\033[0m Service started' >&2
}

stop() {
  if [ ! -f $DAEMON_PIDFILE ] || ! kill -0 $(cat $DAEMON_PIDFILE); then
    echo -e '\033[1;33m[WARN]\033[0m Service not running' >&2
    return 1
  fi
  echo -e '\033[0;34m[NOTIFY]\033[0m Stopping service…' >&2
  kill $(cat $DAEMON_PIDFILE) && rm -f $DAEMON_PIDFILE
  sleep 5
  echo -e '\033[0;32m[OK]\033[0m Service stopped' >&2
}

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