#!/bin/bash
# configure-cloudflare-tunnel.sh
# Configuration script for Cloudflare Tunnel VM

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $*"
}

log_success() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] ✅${NC} $*"
}

log_warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] ⚠️${NC} $*"
}

log_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

# Get VM IP address
get_vm_ip() {
    local vm_name=$1
    local ip
    
    ip=$(kubectl get proxmoxvm "${vm_name}" -n default -o jsonpath='{.status.ipAddress}' 2>/dev/null || echo "")
    
    if [ -z "${ip}" ] || [ "${ip}" = "<none>" ]; then
        log_warning "VM IP not yet assigned. Waiting..."
        return 1
    fi
    
    echo "${ip}"
}

# Wait for VM to be ready
wait_for_vm() {
    local vm_name=$1
    local max_attempts=30
    local attempt=0
    
    log "Waiting for ${vm_name} to be ready..."
    
    while [ ${attempt} -lt ${max_attempts} ]; do
        local ip
        ip=$(get_vm_ip "${vm_name}" 2>/dev/null || echo "")
        
        if [ -n "${ip}" ] && [ "${ip}" != "<none>" ]; then
            log_success "${vm_name} is ready at ${ip}"
            echo "${ip}"
            return 0
        fi
        
        attempt=$((attempt + 1))
        sleep 10
    done
    
    log_error "${vm_name} did not become ready in time"
    return 1
}

# Generate Cloudflare Tunnel configuration
generate_tunnel_config() {
    local config_file=$1
    local tunnel_name=$2
    local credentials_file=$3
    
    cat > "${config_file}" <<EOF
# Cloudflare Tunnel Configuration for SMOM-DBIS-138
# Generated: $(date +'%Y-%m-%d %H:%M:%S')

tunnel: ${tunnel_name}
credentials-file: ${credentials_file}

ingress:
  # Nginx Proxy
  - hostname: nginx-proxy.sankofa.nexus
    service: http://nginx-proxy-vm:80
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s

  # SMOM-DBIS-138 Services
  - hostname: smom-api.sankofa.nexus
    service: http://smom-services:8080
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s

  - hostname: smom-blockscout.sankofa.nexus
    service: http://smom-blockscout:4000
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s

  - hostname: smom-monitoring.sankofa.nexus
    service: http://smom-monitoring:3000
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s

  # RPC Nodes
  - hostname: smom-rpc-01.sankofa.nexus
    service: http://smom-rpc-node-01:8545
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s

  - hostname: smom-rpc-02.sankofa.nexus
    service: http://smom-rpc-node-02:8545
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s

  # Catch-all rule (must be last)
  - service: http_status:404

# Logging
loglevel: info
logfile: /var/log/cloudflared/tunnel.log

# Metrics
metrics: 0.0.0.0:9090

# Health check
health-probe:
  enabled: true
  path: /health
  port: 8080
EOF
}

main() {
    log "=========================================="
    log "Cloudflare Tunnel Configuration Script"
    log "=========================================="
    log ""
    
    # Check if VM exists
    if ! kubectl get proxmoxvm cloudflare-tunnel-vm -n default &>/dev/null; then
        log_error "cloudflare-tunnel-vm not found. Please deploy it first."
        exit 1
    fi
    
    # Wait for VM to be ready
    local vm_ip
    vm_ip=$(wait_for_vm "cloudflare-tunnel-vm")
    
    if [ -z "${vm_ip}" ]; then
        log_error "Failed to get VM IP address"
        exit 1
    fi
    
    log_success "Cloudflare Tunnel VM is ready at ${vm_ip}"
    log ""
    log "Next steps:"
    log "1. Create a Cloudflare Tunnel in the Cloudflare dashboard"
    log "2. Copy the tunnel token/credentials"
    log "3. SSH into the VM: ssh admin@${vm_ip}"
    log "4. Place tunnel credentials at: /etc/cloudflared/tunnel-credentials.json"
    log "5. Update tunnel configuration at: /etc/cloudflared/config.yaml"
    log "6. Start the tunnel service: sudo systemctl start cloudflared"
    log "7. Enable auto-start: sudo systemctl enable cloudflared"
    log ""
    log "Example tunnel configuration:"
    log "  ${PROJECT_ROOT}/docs/configs/cloudflare/tunnel-config.yaml"
    log ""
    log "To create a tunnel via API, use:"
    log "  ${PROJECT_ROOT}/scripts/configure-cloudflare.sh"
    log ""
}

main "$@"

