#!/bin/sh
# WiFi hotplug script - triggers on wireless events
# Install to /etc/hotplug.d/wireless/
#
# Events emitted (must match client2server-unified.lua's handler):
#   wifi_connected / wifi_disconnected
#
# 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

case "$ACTION" in
    associate|associated)
        if [ -n "$MACADDR" ]; then
            log_msg "WiFi CONNECTED: $MACADDR on $INTERFACE"
            send_event "wifi_connected" \
                "{\"mac\":\"$MACADDR\",\"interface\":\"$INTERFACE\"}"
        fi
        ;;
    disassociate|disassociated|deauth|expired)
        if [ -n "$MACADDR" ]; then
            log_msg "WiFi DISCONNECTED: $MACADDR on $INTERFACE"
            send_event "wifi_disconnected" \
                "{\"mac\":\"$MACADDR\",\"interface\":\"$INTERFACE\"}"
        fi
        ;;
esac
