#!/bin/sh
### BEGIN INIT INFO
# Provides:          samcatd
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       <DESCRIPTION>
### END INIT INFO

SCRIPT='/usr/local/bin/samcatd -f /etc/samcatd/tunnels.ini'
RUNAS=samcatd

PIDFILE=/var/run/samcatd/samcatd.pid
RUNFOLDER=/var/run/samcatd
LOGFILE=/var/log/samcatd/samcatd.log

start() {
  if [ -f "$PIDFILE" ]; then
    echo 'Service already running' >&2
    return 1
  fi
  echo 'Starting destination-isolating proxy service…' >&2
  start-stop-daemon -S -b -q -d "$RUNFOLDER" -g "$RUNAS" -c "$RUNAS" -p "$PIDFILE" \
    --startas /bin/bash -- -c "exec $SCRIPT > $LOGFILE 2>&1"
  echo $! > "$PIDFILE"
  echo "Service started: $SCRIPT" >&2
  cat "$PIDFILE" >&2
}

stop() {
  if [ ! -f "$PIDFILE" ]; then
    echo 'Service not running' >&2
    return 1
  fi
  echo 'Stopping destination-isolating proxy service…' >&2
  start-stop-daemon -K -q -d "$RUNFOLDER" -g "$RUNAS" -c "$RUNAS" -p "$PIDFILE" \
    --startas /bin/bash -- -c "exec $SCRIPT > $LOGFILE 2>&1"
  echo "Service stopped: $SCRIPT" >&2
  rm -f "$PIDFILE"
}

status() {
  if [ -f "$PIDFILE" ]; then
    start-stop-daemon -T -q -d "$RUNFOLDER" -g "$RUNAS" -c "$RUNAS" -p "$PIDFILE" \
      --startas /bin/bash -- -c "exec $SCRIPT > $LOGFILE 2>&1"
    echo 'Currently open pipes:' >&2
    ls /var/run/samcatd/* >&2
    tail $LOGFILE >&2
    return 1
  else
    echo 'Service not running' >&2
    ls /var/run/samcatd >&2
    return 1
  fi
  echo 'Starting destination-isolating proxy service…' >&2
}

uninstall() {
  echo -n "Are you really sure you want to uninstall this service? That cannot be undone. [yes|No] "
  local SURE
  read SURE
  if [ "$SURE" = "yes" ]; then
    stop
    rm -f "$PIDFILE"
    echo "Notice: log file is not be removed: '$LOGFILE'" >&2
    update-rc.d -f samcatd remove
    rm -fv "$0"
  fi
}

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