#!/bin/bash
#
# pxe-dhcp-hook.sh - dnsmasq dhcp-script hook.
#
# Runs every time a PXE client gets/changes/releases a DHCP lease on
# 10.9.100.0/24. Flushes conntrack entries and drops any lingering
# TCP sockets for that client IP. Prevents stale server-side state from
# causing "System error 53 - network path not found" when a WinPE client
# re-images the same machine without a clean SMB session teardown.
#
# dnsmasq calls this with argv:
#   $1 = action (add | old | del)
#   $2 = mac address
#   $3 = client IP
#   $4 = hostname (may be empty)
#
# Must exit quickly; dnsmasq waits for it. Logs to syslog via logger.

set +e

action="$1"
mac="$2"
ip="$3"
host="${4:-}"

[ -z "$ip" ] && exit 0

case "$action" in
    add|del)
        /usr/sbin/conntrack -D -s "$ip" >/dev/null 2>&1
        /usr/sbin/conntrack -D -d "$ip" >/dev/null 2>&1
        /usr/bin/ss -K "dst = $ip"  >/dev/null 2>&1
        /usr/bin/ss -K "src = $ip"  >/dev/null 2>&1
        logger -t pxe-dhcp-hook "cleared stale state for $action $ip ($mac${host:+ $host})"
        ;;
esac

exit 0
