#!/usr/bin/env bash
# Configure Cloudflare Tunnel Route for explorer.d-bis.org
# Usage: ./configure-cloudflare-tunnel-route.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${ENV_FILE:-$SCRIPT_DIR/../.env}"

DOMAIN="${DOMAIN:-d-bis.org}"
EXPLORER_DOMAIN="explorer.d-bis.org"
EXPLORER_IP="${EXPLORER_IP:-192.168.11.140}"
EXPLORER_PORT="${EXPLORER_PORT:-80}"
TUNNEL_ID="${TUNNEL_ID:-10ab22da-8ea3-4e2e-a896-27ece2211a05}"

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

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

# Load environment variables
if [ -f "$ENV_FILE" ]; then
    source "$ENV_FILE"
fi

CLOUDFLARE_ACCOUNT_ID="${CLOUDFLARE_ACCOUNT_ID:-}"
CLOUDFLARE_API_KEY="${CLOUDFLARE_API_KEY:-}"
CLOUDFLARE_EMAIL="${CLOUDFLARE_EMAIL:-}"
CLOUDFLARE_API_TOKEN="${CLOUDFLARE_API_TOKEN:-}"

# Determine auth method
if [ -n "$CLOUDFLARE_API_TOKEN" ]; then
    AUTH_HEADERS=(-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN")
elif [ -n "$CLOUDFLARE_API_KEY" ] && [ -n "$CLOUDFLARE_EMAIL" ]; then
    AUTH_HEADERS=(-H "X-Auth-Email: $CLOUDFLARE_EMAIL" -H "X-Auth-Key: $CLOUDFLARE_API_KEY")
else
    log_error "No Cloudflare API credentials found"
    exit 1
fi

if [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then
    log_error "CLOUDFLARE_ACCOUNT_ID not set"
    exit 1
fi

log_info "Configuring tunnel route for $EXPLORER_DOMAIN"
log_info "Tunnel ID: $TUNNEL_ID"
if [ "$EXPLORER_PORT" = "443" ]; then
    log_info "Service: https://$EXPLORER_IP:$EXPLORER_PORT"
else
    log_info "Service: http://$EXPLORER_IP:$EXPLORER_PORT"
fi

# Get current tunnel configuration
log_info "Fetching current tunnel configuration..."
CURRENT_CONFIG=$(curl -s -X GET "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/cfd_tunnel/$TUNNEL_ID/configurations" \
    "${AUTH_HEADERS[@]}" \
    -H "Content-Type: application/json")

if ! echo "$CURRENT_CONFIG" | jq -e '.success' >/dev/null 2>&1; then
    log_error "Failed to fetch tunnel configuration"
    echo "$CURRENT_CONFIG" | jq '.' 2>/dev/null || echo "$CURRENT_CONFIG"
    exit 1
fi

# Extract current ingress rules
CURRENT_INGRESS=$(echo "$CURRENT_CONFIG" | jq -c '.result.config.ingress // []')

# Check if explorer route already exists
if echo "$CURRENT_INGRESS" | jq -e ".[] | select(.hostname == \"$EXPLORER_DOMAIN\")" >/dev/null 2>&1; then
    log_warn "Route for $EXPLORER_DOMAIN already exists"
    log_info "Updating existing route..."
    # Remove existing route
    CURRENT_INGRESS=$(echo "$CURRENT_INGRESS" | jq "[.[] | select(.hostname != \"$EXPLORER_DOMAIN\")]")
fi

# Determine if HTTPS (port 443)
if [ "$EXPLORER_PORT" = "443" ]; then
    SERVICE_URL="https://$EXPLORER_IP:$EXPLORER_PORT"
else
    SERVICE_URL="http://$EXPLORER_IP:$EXPLORER_PORT"
fi

# Build explorer route as array element
EXPLORER_ROUTE=$(jq -n \
    --arg hostname "$EXPLORER_DOMAIN" \
    --arg service "$SERVICE_URL" \
    '[{
        hostname: $hostname,
        service: $service,
        originRequest: {
            noTLSVerify: true
        }
    }]')

# Separate catch-all from other rules
# Catch-all has no hostname and service starting with http_status
CATCH_ALL=$(echo "$CURRENT_INGRESS" | jq '[.[] | select(.hostname == null or .hostname == "" or (.service | startswith("http_status")))]')
OTHER_ROUTES=$(echo "$CURRENT_INGRESS" | jq '[.[] | select(.hostname != null and .hostname != "" and (.service | startswith("http_status") | not))]')

# Build new ingress: explorer route + other routes + catch-all
# If no catch-all exists, add one
if [ "$(echo "$CATCH_ALL" | jq 'length')" -eq 0 ]; then
    CATCH_ALL='[{"service":"http_status:404"}]'
fi

# Concatenate arrays properly
NEW_INGRESS=$(jq -n --argjson explorer "$EXPLORER_ROUTE" --argjson others "$OTHER_ROUTES" --argjson catchall "$CATCH_ALL" '$explorer + $others + $catchall')

# Build complete config
NEW_CONFIG=$(jq -n \
    --argjson ingress "$NEW_INGRESS" \
    '{
        config: {
            ingress: $ingress
        }
    }')

log_info "Updating tunnel configuration..."
RESPONSE=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/cfd_tunnel/$TUNNEL_ID/configurations" \
    "${AUTH_HEADERS[@]}" \
    -H "Content-Type: application/json" \
    --data "$NEW_CONFIG")

if echo "$RESPONSE" | jq -e '.success' >/dev/null 2>&1; then
    log_success "Tunnel route configured successfully!"
    log_info "Route: $EXPLORER_DOMAIN → http://$EXPLORER_IP:$EXPLORER_PORT"
    exit 0
else
    ERROR=$(echo "$RESPONSE" | jq -r '.errors[0].message // "Unknown error"' 2>/dev/null || echo "API call failed")
    log_error "Failed to configure tunnel route: $ERROR"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
    exit 1
fi

