#!/bin/sh
# bty-web PXE deactivation helper.
#
# Invoked by the ``bty`` service user via the entry in
# ``/etc/sudoers.d/bty-web``. Stops the ``bty-pxe-proxy.service``
# and removes the env file at ``/etc/default/bty-pxe-proxy``.
#
# Idempotent: a missing env file / stopped service is treated as
# success ("already deactivated") so the operator can click
# Deactivate from a clean state without seeing an error.
#
# Pairs with ``bty-web-activate-pxe``. The legacy v0.13.x flow
# wrote dnsmasq config at /etc/dnsmasq.d/bty-pxe-active.conf; we
# also clean that up here so an in-place upgrade settles cleanly.

set -eu

ACTIVE=/etc/default/bty-pxe-proxy

# Stop + disable the proxy daemon (and Wants=, the service unit's
# Install section). disable is idempotent.
systemctl stop bty-pxe-proxy.service 2>/dev/null || true
systemctl disable bty-pxe-proxy.service >/dev/null 2>&1 || true

removed_something=0
if [ -f "$ACTIVE" ]; then
    rm -f "$ACTIVE"
    removed_something=1
fi

# Cleanup of the legacy dnsmasq-proxy-DHCP file from v0.13.x.
if [ -f /etc/dnsmasq.d/bty-pxe-active.conf ]; then
    rm -f /etc/dnsmasq.d/bty-pxe-active.conf
    systemctl restart dnsmasq.service
    removed_something=1
fi

if [ "$removed_something" = "1" ]; then
    printf 'PXE deactivated (stopped bty-pxe-proxy.service, cleared %s)\n' "$ACTIVE"
else
    printf 'PXE already inactive (no %s)\n' "$ACTIVE"
fi
