#!/bin/sh
# ==============================================================================
# BuhtaAuto - Keenetic Router On-Device Push Agent
# Runs directly on Keenetic (via Entware or cron) or local network
# Uses Keenetic RCI API: /rci/show/ip/hotspot
# ==============================================================================

# CONFIGURATION
CLOUD_URL="${CLOUD_URL:-http://YOUR_SERVER_IP:8080/api/router/push}"
BRANCH_TOKEN="${BRANCH_TOKEN:-buhta_secret_2026}"
BRANCH_ID="${BRANCH_ID:-branch_2}"
KEENETIC_HOST="${KEENETIC_HOST:-127.0.0.1}"
KEENETIC_USER="${KEENETIC_USER:-admin}"
KEENETIC_PASSWORD="${KEENETIC_PASSWORD:-admin_password}"

# Query Keenetic RCI API for active connected devices
# Keenetic returns {"host": [{"mac":"...", "name":"...", "ip":"...", "active":true, "uptime":123}]}
if command -v ndmc >/dev/null 2>&1; then
    # Native Keenetic CLI tool
    RAW_DATA=$(ndmc -c "show ip hotspot" 2>/dev/null)
else
    # HTTP RCI API call with Basic auth
    RAW_DATA=$(curl -s -u "${KEENETIC_USER}:${KEENETIC_PASSWORD}" "http://${KEENETIC_HOST}/rci/show/ip/hotspot" 2>/dev/null)
fi

if [ -z "$RAW_DATA" ]; then
    echo "Failed to get hotspot data from Keenetic"
    exit 1
fi

TIMESTAMP=$(date +%s)

# Send payload to Cloud API
# Our Cloud backend accepts Keenetic format {"host": [...]} or standard {"devices": [...]}
PAYLOAD="{\"branch_id\":\"$BRANCH_ID\",\"timestamp\":$TIMESTAMP,\"keenetic_data\":$RAW_DATA}"

RESPONSE=$(curl -s -k -X POST "$CLOUD_URL" \
    -H "Content-Type: application/json" \
    -H "X-Branch-Token: $BRANCH_TOKEN" \
    -d "$PAYLOAD" \
    --connect-timeout 8 \
    --max-time 15)

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Keenetic data pushed to cloud. Server response: $RESPONSE"
