#!/bin/bash
set -euo pipefail

# Discover Access Points Script

CONTROLLER="${OMADA_CONTROLLER:-}"
ADMIN_USER="${OMADA_ADMIN:-admin}"
ADMIN_PASSWORD="${OMADA_PASSWORD:-}"
SITE_ID="${SITE_ID:-}"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2
}

error() {
    log "ERROR: $*"
    exit 1
}

check_prerequisites() {
    if [ -z "${CONTROLLER}" ]; then
        error "OMADA_CONTROLLER environment variable is required"
    fi
    
    if [ -z "${ADMIN_PASSWORD}" ]; then
        error "OMADA_PASSWORD environment variable is required"
    fi
}

authenticate() {
    log "Authenticating with Omada Controller..."
    
    TOKEN_RESPONSE=$(curl -k -s -X POST "https://${CONTROLLER}:8043/api/v2/login" \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"${ADMIN_USER}\",\"password\":\"${ADMIN_PASSWORD}\"}")
    
    TOKEN=$(echo "${TOKEN_RESPONSE}" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
    
    if [ -z "${TOKEN}" ]; then
        error "Authentication failed"
    fi
    
    echo "${TOKEN}"
}

discover_aps() {
    TOKEN=$1
    
    if [ -n "${SITE_ID}" ]; then
        ENDPOINT="/api/v2/sites/${SITE_ID}/access-points"
    else
        ENDPOINT="/api/v2/access-points"
    fi
    
    log "Discovering access points..."
    
    RESPONSE=$(curl -k -s -X GET "https://${CONTROLLER}:8043${ENDPOINT}" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "${RESPONSE}" | python3 -m json.tool 2>/dev/null || echo "${RESPONSE}"
}

main() {
    log "Starting access point discovery..."
    
    check_prerequisites
    TOKEN=$(authenticate)
    discover_aps "${TOKEN}"
    
    log "Discovery completed!"
}

main "$@"

