#!/bin/sh
set -u
base=/data/opt/alice-backend
pidfile=/tmp/alice-music-supervisor.pid
is_ours() {
  case "$1" in ''|*[!0-9]*) return 1 ;; esac
  [ -r "/proc/$1/cmdline" ] && tr '\0' '\n' < "/proc/$1/cmdline" | grep -qx "$base/spotify-supervisor.sh"
}
case "${1:-}" in
  start)
    [ -f "$base/stock-disabled" ] || exit 0
    if [ -r "$pidfile" ]; then p=$(cat "$pidfile"); is_ours "$p" && exit 0; fi
    setsid "$base/spotify-supervisor.sh" </dev/null >/dev/null 2>&1 &
    umask 077
    echo $! > "$pidfile"
    ;;
  stop)
    [ -r "$pidfile" ] || exit 0
    p=$(cat "$pidfile")
    if is_ours "$p"; then
      kill -TERM "$p" 2>/dev/null || true
      for second in 1 2 3 4 5 6 7 8 9 10; do is_ours "$p" || break; sleep 1; done
      if is_ours "$p"; then echo 'Music supervisor failed to stop' >&2; exit 1; fi
    fi
    rm -f "$pidfile"
    ;;
  restart) "$0" stop && "$0" start ;;
  *) echo "Usage: $0 {start|stop|restart}" >&2; exit 2 ;;
esac
