#!/bin/sh
# bty-web PXE daemon-control helper.
#
# Invoked by the ``bty`` service user via the entry in
# ``/etc/sudoers.d/bty-web``. Performs ``systemctl <action> <unit>``
# for the two PXE-stack daemons, where action and unit are both
# from a strict allowlist. This lets the /ui/settings page surface
# per-daemon Start / Stop / Restart buttons for triage WITHOUT
# granting the web user free-form systemctl access.
#
# Why a separate helper from activate / deactivate: those two
# helpers wrap an opinionated workflow (write env file, restart
# dnsmasq, enable + start the pair). The diagnostic knobs are
# orthogonal -- "restart just the TFTP daemon to test something"
# shouldn't touch the env file or dnsmasq. Splitting keeps the
# blast radius of each helper minimal.
#
# Args:
#   $1  action: ``start`` | ``stop`` | ``restart``
#   $2  unit:   ``bty-pxe-proxy`` | ``bty-tftp`` (without ``.service``)
#
# Allowlist (intentionally narrow). ``enable`` / ``disable`` are
# deliberately not exposed -- boot-time autostart is a property of
# the activate / deactivate workflow, not a per-daemon knob.

set -eu

if [ $# -ne 2 ]; then
    printf 'usage: %s <start|stop|restart> <bty-pxe-proxy|bty-tftp>\n' "$0" >&2
    exit 64
fi

ACTION=$1
UNIT=$2

case "$ACTION" in
    start|stop|restart) ;;
    *) printf 'bad action: %s (allowed: start, stop, restart)\n' "$ACTION" >&2; exit 64 ;;
esac

case "$UNIT" in
    bty-pxe-proxy|bty-tftp) ;;
    *) printf 'bad unit: %s (allowed: bty-pxe-proxy, bty-tftp)\n' "$UNIT" >&2; exit 64 ;;
esac

# ``systemctl start`` of a unit with ConditionPathExists= that's
# unmet exits 0 with no observable side-effect. That's the right
# behaviour for us: when /etc/default/bty-pxe-proxy is missing,
# the daemon stays inactive cleanly rather than flapping.
systemctl "$ACTION" "${UNIT}.service"
