#!/bin/bash
set -euo pipefail

# TP-Link Omada Controller Setup Script

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

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
    
    if ! command -v curl &> /dev/null; then
        error "curl is required but not installed"
    fi
}

test_controller_connectivity() {
    log "Testing connectivity to Omada Controller at ${CONTROLLER}..."
    
    if curl -k -s --connect-timeout 5 "https://${CONTROLLER}:8043" > /dev/null; then
        log "Controller is reachable"
        return 0
    else
        error "Cannot reach controller at ${CONTROLLER}:8043"
    fi
}

verify_authentication() {
    log "Verifying authentication..."
    
    RESPONSE=$(curl -k -s -X POST "https://${CONTROLLER}:8043/api/v2/login" \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"${ADMIN_USER}\",\"password\":\"${ADMIN_PASSWORD}\"}")
    
    if echo "${RESPONSE}" | grep -q "token"; then
        log "Authentication successful"
        return 0
    else
        error "Authentication failed. Please check credentials."
    fi
}

create_site() {
    if [ -z "${SITE_NAME}" ]; then
        log "SITE_NAME not provided, skipping site creation"
        return 0
    fi
    
    log "Creating site: ${SITE_NAME}..."
    
    # Get authentication token
    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 "Failed to get authentication token"
    fi
    
    # Create site
    SITE_RESPONSE=$(curl -k -s -X POST "https://${CONTROLLER}:8043/api/v2/sites" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer ${TOKEN}" \
        -d "{\"name\":\"${SITE_NAME}\",\"timezone\":\"UTC\"}")
    
    if echo "${SITE_RESPONSE}" | grep -q "id"; then
        SITE_ID=$(echo "${SITE_RESPONSE}" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
        log "Site created successfully with ID: ${SITE_ID}"
    else
        log "Warning: Site creation may have failed or site already exists"
    fi
}

main() {
    log "Starting Omada Controller setup..."
    
    check_prerequisites
    test_controller_connectivity
    verify_authentication
    create_site
    
    log "Omada Controller setup completed!"
    log ""
    log "Next steps:"
    log "1. Configure access points: ./provision-ap.sh"
    log "2. Create SSIDs: ./create-ssid.sh"
    log "3. Set up network policies: ./create-policy.sh"
}

main "$@"

