#!/bin/sh
# DHCP hotplug script - triggers on DHCP events
# Install to /etc/hotplug.d/dhcp/
#
# Event names match package/src/client2server-unified.lua:
#   dhcp_lease_new / dhcp_lease_expire

# 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 DHCP events
#   add      - new lease (or renew with new IP)
#   del      - lease released
#   remove   - same as del, alias used by some builds
case "$ACTION" in
    add|update|old)
        if [ -n "$MAC" ] && [ -n "$IP" ]; then
            log "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 "DHCP LEASE EXPIRE: $MAC -> $IP"
            send_event "dhcp_lease_expire" "{\"mac\":\"$MAC\",\"old_ip\":\"$IP\"}"
        fi
        ;;
esac
