#!/bin/sh
set -eu

unit=gitr-vpn-runtimed.service
binary=/usr/sbin/gitr-vpn-runtimed
marker=/run/gitr-vpn-runtime-handoff.skip-guard

# Older packages tied every WireGuard unit to the runtime with Requires=. That
# relationship stops the kernel tunnel whenever the management runtime is
# replaced. Convert only product-owned drop-ins before the handoff and reload
# the unit graph so active tunnels remain independent.
dropins_changed=0
for dropin in /etc/systemd/system/wg-quick@*.service.d/octava-corporate.conf; do
    [ -e "$dropin" ] || continue
    if grep -qx 'Requires=gitr-vpn-runtimed.service' "$dropin"; then
        sed -i 's/^Requires=gitr-vpn-runtimed.service$/Wants=gitr-vpn-runtimed.service/' "$dropin"
        dropins_changed=1
    fi
done
if [ "$dropins_changed" -eq 1 ]; then
    systemctl daemon-reload
fi

if ! systemctl is-active --quiet "$unit"; then
    deb-systemd-invoke start "$unit" >/dev/null
    exit 0
fi

current_pid="$(systemctl show --property=MainPID --value "$unit")"
if [ "$current_pid" -gt 0 ] 2>/dev/null && cmp -s "/proc/$current_pid/exe" "$binary"; then
    deb-systemd-invoke reload "$unit" >/dev/null
    exit 0
fi

# The runtime does not own WireGuard interfaces. Consume a one-shot marker in
# ExecStopPost so the safety guard cannot replace active firewall rules during
# this verified package handoff. Any ordinary stop or crash still runs guard.
umask 077
: >"$marker"
trap 'rm -f "$marker"' EXIT HUP INT TERM
systemctl kill --kill-whom=main --signal=KILL "$unit"

attempt=0
while [ "$attempt" -lt 45 ]; do
    attempt=$((attempt + 1))
    current_pid="$(systemctl show --property=MainPID --value "$unit")"
    if systemctl is-active --quiet "$unit" &&
       [ "$current_pid" -gt 0 ] 2>/dev/null &&
       cmp -s "/proc/$current_pid/exe" "$binary"; then
        systemctl reset-failed "$unit" >/dev/null 2>&1 || true
        rm -f "$marker"
        trap - EXIT HUP INT TERM
        exit 0
    fi
    sleep 1
done

echo "GITR runtime binary handoff failed" >&2
exit 1
