#!/bin/sh
base=/data/opt/alice-backend
pidfile=/tmp/alice-supervisor.pid
is_supervisor() {
  case "$1" in ''|*[!0-9]*) return 1 ;; esac
  [ -r "/proc/$1/cmdline" ] || return 1
  # Match a complete argv element, not a substring or an unrelated reused PID.
  tr '\000' '\n' < "/proc/$1/cmdline" | grep -Fqx "$base/station-supervisor.sh"
}
case "${1:-}" in
 start)
  [ -f "$base/stock-disabled" ] || exit 0
  if [ -f "$pidfile" ]; then
    p=$(cat "$pidfile")
    if is_supervisor "$p"; then exit 0; fi
    rm -f "$pidfile"
  fi
  setsid "$base/station-supervisor.sh" </dev/null >/dev/null 2>&1 &
  echo $! > "$pidfile"
  ;;
 stop)
  if [ -f "$pidfile" ]; then
    p=$(cat "$pidfile")
    if is_supervisor "$p"; then
      kill -TERM "$p" 2>/dev/null || :
      n=0
      while is_supervisor "$p"; do
        if [ "$n" -ge 25 ]; then echo 'Station supervisor did not stop' >&2; exit 1; fi
        sleep 1
        n=$((n + 1))
      done
    fi
    rm -f "$pidfile"
  fi
  ;;
 restart) "$0" stop && "$0" start ;;
 *) echo "Usage: $0 {start|stop|restart}" >&2; exit 2 ;;
esac
