#!/bin/sh
# DHCP hotplug script - triggers on DHCP events
# Install to /etc/hotplug.d/dhcp/
#
# Events emitted (must match client2server-unified.lua's handler):
#   dhcp_lease_new / dhcp_lease_expire
#
# Events are spooled to /var/run/client2server/buffer and the Lua agent
# is woken via SIGHUP. If the agent is offline (internet down), events
# accumulate on disk and are flushed on reconnect.

SCRIPT_DIR="$(dirname "$0")"
# Source the shared lib from its canonical install location.
# Falls back to the development path (hotplug/_lib.sh) for tests.
if [ -f /usr/share/client2server/hotplug-lib.sh ]; then
    # shellcheck disable=SC1091
    . /usr/share/client2server/hotplug-lib.sh
elif [ -f "$SCRIPT_DIR/_lib.sh" ]; then
    # shellcheck disable=SC1091
    . "$SCRIPT_DIR/_lib.sh"
else
    logger -t client2server-hotplug -p user.err "hotplug-lib.sh not found"
    exit 1
fi

# Handle DHCP events
#   add    - new lease (or renew with new IP)
#   update - lease renewed (same IP, new expiry)
#   old    - lease rebind/old
#   del    - lease released
#   remove - alias for del in some builds
case "$ACTION" in
    add|update|old)
        if [ -n "$MAC" ] && [ -n "$IP" ]; then
            log_msg "DHCP LEASE NEW: $MAC -> $IP ($HOSTNAME)"
            send_event "dhcp_lease_new" \
                "{\"mac\":\"$MAC\",\"ip\":\"$IP\",\"hostname\":\"$HOSTNAME\"}"
        fi
        ;;
    del|remove)
        if [ -n "$MAC" ] && [ -n "$IP" ]; then
            log_msg "DHCP LEASE EXPIRE: $MAC -> $IP"
            send_event "dhcp_lease_expire" \
                "{\"mac\":\"$MAC\",\"old_ip\":\"$IP\"}"
        fi
        ;;
esac
