#!/usr/bin/env bash
# Configure tunnel-r630-02 to be ready for migration/token generation
# This ensures the tunnel has proper configuration before getting a token

set -euo pipefail

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

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Load .env
if [ -f "$TUNNELS_DIR/../../.env" ]; then
    source "$TUNNELS_DIR/../../.env" 2>/dev/null || true
fi

if [[ -z "${CLOUDFLARE_ACCOUNT_ID:-}" ]] || [[ -z "${CLOUDFLARE_API_KEY:-}" ]] || [[ -z "${CLOUDFLARE_EMAIL:-}" ]]; then
    log_error "Cloudflare credentials not found in .env"
    exit 1
fi

TUNNEL_ID="0876f12b-64d7-4927-9ab3-94cb6cf48af9"
HOSTNAME="r630-02.d-bis.org"
TARGET="https://192.168.11.12:8006"

log_info "=== Configuring tunnel-r630-02 for Migration ==="
echo ""

# Function to make API request
cf_api_request() {
    local method="$1"
    local endpoint="$2"
    local data="${3:-}"
    
    local url="https://api.cloudflare.com/client/v4${endpoint}"
    local temp_file=$(mktemp)
    local http_code
    
    if [[ -n "$data" ]]; then
        http_code=$(curl -s -o "$temp_file" -w "%{http_code}" \
            -X "$method" "$url" \
            -H "X-Auth-Email: ${CLOUDFLARE_EMAIL}" \
            -H "X-Auth-Key: ${CLOUDFLARE_API_KEY}" \
            -H "Content-Type: application/json" \
            -d "$data" 2>/dev/null)
    else
        http_code=$(curl -s -o "$temp_file" -w "%{http_code}" \
            -X "$method" "$url" \
            -H "X-Auth-Email: ${CLOUDFLARE_EMAIL}" \
            -H "X-Auth-Key: ${CLOUDFLARE_API_KEY}" \
            -H "Content-Type: application/json" 2>/dev/null)
    fi
    
    local response=$(cat "$temp_file" 2>/dev/null || echo "")
    rm -f "$temp_file"
    
    if [[ "$http_code" != "200" ]] && [[ "$http_code" != "201" ]]; then
        log_error "API request failed (HTTP $http_code)"
        echo "$response" | jq -r '.errors[0].message // "Unknown error"' 2>/dev/null || echo "$response"
        return 1
    fi
    
    echo "$response"
}

# Step 1: Ensure tunnel configuration exists
log_info "Step 1: Configuring tunnel route..."

CONFIG_DATA=$(jq -n \
    --arg hostname "$HOSTNAME" \
    --arg target "$TARGET" \
    '{
        config: {
            ingress: [
                {
                    hostname: $hostname,
                    service: $target,
                    originRequest: {
                        noHappyEyeballs: true,
                        connectTimeout: "30s",
                        tcpKeepAlive: "30s",
                        keepAliveConnections: 100,
                        keepAliveTimeout: "90s",
                        disableChunkedEncoding: true,
                        noTLSVerify: true
                    }
                },
                {
                    service: "http_status:404"
                }
            ]
        }
    }')

response=$(cf_api_request "PUT" "/accounts/${CLOUDFLARE_ACCOUNT_ID}/cfd_tunnel/${TUNNEL_ID}/configurations" "$CONFIG_DATA" 2>&1)

if echo "$response" | jq -e '.success' >/dev/null 2>&1; then
    log_success "Tunnel route configured"
else
    log_error "Failed to configure tunnel route"
    echo "$response" | jq -r '.errors[0].message // "Unknown error"' 2>/dev/null
    exit 1
fi

# Step 2: Create local config file
log_info "Step 2: Creating local config file..."

CONFIG_FILE="$TUNNELS_DIR/configs/tunnel-r630-02.yml"

cat > "$CONFIG_FILE" <<EOF
# Cloudflare Tunnel Configuration for r630-02 Proxmox Host
# Tunnel Name: tunnel-r630-02
# Domain: r630-02.d-bis.org
# Target: 192.168.11.12:8006 (Proxmox UI)

tunnel: $TUNNEL_ID
credentials-file: /etc/cloudflared/credentials-r630-02.json

ingress:
  # Proxmox UI - r630-02
  - hostname: $HOSTNAME
    service: $TARGET
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      # Allow self-signed certificates (Proxmox uses self-signed)
      noTLSVerify: true

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

# Metrics endpoint (optional, for monitoring)
metrics: 127.0.0.1:9093

# Logging
loglevel: info

# Grace period for shutdown
gracePeriod: 30s
EOF

log_success "Config file created: $CONFIG_FILE"

# Step 3: Check tunnel status
log_info "Step 3: Checking tunnel status..."
response=$(cf_api_request "GET" "/accounts/${CLOUDFLARE_ACCOUNT_ID}/cfd_tunnel/${TUNNEL_ID}" 2>&1)

if echo "$response" | jq -e '.result' >/dev/null 2>&1; then
    status=$(echo "$response" | jq -r '.result.status // "unknown"')
    remote_config=$(echo "$response" | jq -r '.result.remote_config // false')
    
    log_info "Tunnel status: $status"
    log_info "Remote config: $remote_config"
    
    if [[ "$status" == "healthy" ]] && [[ "$remote_config" == "true" ]]; then
        log_success "Tunnel is ready for migration!"
    else
        log_warn "Tunnel needs to be connected to become healthy"
        log_info "Once you install and start the tunnel, it will become healthy"
    fi
fi

echo ""
log_success "=== Configuration Complete ==="
log_info "Next steps:"
log_info "1. Get token from Cloudflare Dashboard:"
log_info "   https://one.dash.cloudflare.com/ → Zero Trust → Networks → Tunnels → tunnel-r630-02"
log_info "2. Install with: sudo cloudflared service install <token>"
log_info "3. Or use the install script once you have the token"

