#!/bin/sh
# WiFi hotplug script - triggers on wireless events
# Install to /etc/hotplug.d/wireless/
#
# Event names match package/src/client2server-unified.lua:
#   wifi_connected / wifi_disconnected

# Source UCI config (set by /etc/init.d/client2server)
SERVER_URL="${SERVER_URL:-}"
ROUTER_ID="${ROUTER_ID:-}"
TOKEN="${TOKEN:-}"

if [ -z "$SERVER_URL" ] || [ -z "$ROUTER_ID" ]; then
    # Fall back to UCI directly (when called outside init.d context)
    SERVER_URL=$(uci get client2server.server.url 2>/dev/null)
    ROUTER_ID=$(uci get client2server.router.id 2>/dev/null)
    TOKEN=$(uci get client2server.server.token 2>/dev/null)
fi

# Final fallback (sane default)
SERVER_URL="${SERVER_URL:-http://127.0.0.1:3843}"
ROUTER_ID="${ROUTER_ID:-$(cat /proc/sys/kernel/hostname 2>/dev/null || echo unknown)}"

log() {
    logger -t client2server-hotplug -p user.info "$1"
}

send_event() {
    local event_type="$1"
    local data="$2"

    json="{\"router_id\":\"$ROUTER_ID\",\"event\":\"$event_type\",\"data\":$data}"

    if [ -n "$TOKEN" ]; then
        curl -s -m 3 -X POST "$SERVER_URL/api/events" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $TOKEN" \
            -d "$json" >/dev/null 2>&1
    else
        curl -s -m 3 -X POST "$SERVER_URL/api/events" \
            -H "Content-Type: application/json" \
            -d "$json" >/dev/null 2>&1
    fi

    log "Sent: $event_type"
}

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