#!/bin/bash
set -u

# Pin PATH rather than rely on sudoers secure_path being set.
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH

usage() {
  echo "usage: unifi-protect-systemctl stop|start|restart|enable|enable --now|disable|disable --now msr|msp|ds|unifi-access|unifi-protect|unifi-homekit|avahi-daemon|homekit-provision" >&2
  exit 1
}

is_member() {
  local needle="$1"
  shift
  for candidate in "$@"; do
    [ "$candidate" = "$needle" ] && return 0
  done
  return 1
}

[ $# -ge 2 ] || usage

service="${*: -1}"
action="${*:1:$(($#-1))}"

is_member "$action" stop start restart enable "enable --now" disable "disable --now" || usage
is_member "$service" msr msp ds unifi-access unifi-protect unifi-homekit avahi-daemon homekit-provision || usage

# msr/msp/ds starts don't wait for the unit to report "active". Decided here, not by the caller.
no_block=""
if [ "$action" = "start" ] && is_member "$service" msr msp ds; then
  no_block="--no-block"
fi

# Bound the client here: the unprivileged caller cannot signal this process. 305s leaves the
# unit's own 300s start/stop timeout a margin.
# $action may be two words ("enable --now"); word-splitting is intentional on an allow-listed value.
if [ -n "$no_block" ]; then
  exec /usr/bin/timeout -k 5 305 /bin/systemctl "$no_block" $action "$service"
else
  exec /usr/bin/timeout -k 5 305 /bin/systemctl $action "$service"
fi
