#!/bin/sh
# bty-web PXE activation helper.
#
# Invoked by the ``bty`` service user via the entry in
# ``/etc/sudoers.d/bty-web``. Writes the dnsmasq proxy-DHCP block
# to ``/etc/dnsmasq.d/bty-pxe-active.conf`` and restarts
# ``dnsmasq.service`` so the new config takes effect.
#
# The shipped ``/etc/dnsmasq.d/bty-pxe.conf`` keeps the chain
# directives commented out as documentation; the active config goes
# in a separate file so the original stays as the canonical
# example. Removing the active file and ``systemctl restart
# dnsmasq`` deactivates PXE again.
#
# Args:
#   $1  network interface (e.g. ``eth0``, ``ens18``)
#   $2  subnet network address (e.g. ``192.168.1.0``)

set -eu

if [ $# -ne 2 ]; then
    printf 'usage: %s <interface> <subnet>\n' "$0" >&2
    exit 64
fi

IFACE=$1
SUBNET=$2

# Validate inputs even though the caller (bty-web) already
# validates - defence in depth: this script runs as root, so refuse
# anything that doesn't match the expected character classes.
case "$IFACE" in
    "" | *[!a-zA-Z0-9_-]*) printf 'bad interface name: %s\n' "$IFACE" >&2; exit 64 ;;
esac
case "$SUBNET" in
    "" | *[!0-9.]*) printf 'bad subnet: %s\n' "$SUBNET" >&2; exit 64 ;;
esac

ACTIVE=/etc/dnsmasq.d/bty-pxe-active.conf
TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT

cat > "$TMP" <<EOF
# Generated by bty-web-activate-pxe.
# Removing this file and restarting dnsmasq deactivates the chain.

bind-interfaces
interface=$IFACE
dhcp-range=$SUBNET,proxy

dhcp-match=set:bios,option:client-arch,0
dhcp-match=set:efi,option:client-arch,7
dhcp-match=set:efi,option:client-arch,9
dhcp-userclass=set:ipxe,iPXE

dhcp-boot=tag:!ipxe,tag:bios,undionly.kpxe
dhcp-boot=tag:!ipxe,tag:efi,ipxe.efi
dhcp-boot=tag:ipxe,http://\${next-server}:8080/pxe-bootstrap.ipxe
EOF

chown root:root "$TMP"
chmod 0644 "$TMP"
mv "$TMP" "$ACTIVE"
trap - EXIT

systemctl restart dnsmasq.service

printf 'PXE activated on %s for %s\n' "$IFACE" "$SUBNET"
