#!/bin/sh
# ==============================================================================
# BuhtaAuto - Xiaomi Router On-Device Push Agent
# Runs directly on Xiaomi router (OpenWrt/MiWiFi) via cron
# Requires: SSH access enabled on router, curl
# ==============================================================================

# 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_1}"

# Check if curl is available
if ! command -v curl >/dev/null 2>&1; then
    echo "curl not found on router! Install or use wget"
    exit 1
fi

# Fetch device list directly from Xiaomi ubus (no login/token needed locally!)
RAW_DATA=$(ubus call misystem devicelist 2>/dev/null)

if [ -z "$RAW_DATA" ]; then
    echo "ubus call returned empty data"
    exit 1
fi

TIMESTAMP=$(date +%s)

# Transform ubus JSON output to Cloud API payload format
# Xiaomi ubus outputs: {"code":0, "list":[...]}
# We wrap it with branch_id and timestamp
PAYLOAD=$(cat <<EOF
{
  "branch_id": "$BRANCH_ID",
  "timestamp": $TIMESTAMP,
  "devices": $(echo "$RAW_DATA" | sed -n 's/.*"list":\s*\[\([^]]*\)\].*/[\1]/p')
}
EOF
)

# Fallback if sed fails on single-line json:
if [ -z "$PAYLOAD" ] || [ "$PAYLOAD" = "{" ]; then
    PAYLOAD="{\"branch_id\":\"$BRANCH_ID\",\"timestamp\":$TIMESTAMP,\"devices\":[]}"
fi

# Send to cloud backend
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')] Pushed to cloud. Server response: $RESPONSE"
