#!/usr/bin/env bash
# Install all 3 Cloudflare tunnels using tokens
# Usage: ./install-all-tunnels.sh <ml110-token> <r630-01-token> <r630-02-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"; }

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"
VMID="${VMID:-102}"

declare -A TUNNELS=(
    ["ml110"]="tunnel-ml110:ccd7150a-9881-4b8c-a105-9b4ead6e69a2:ml110-01.d-bis.org:https://192.168.11.10:8006"
    ["r630-01"]="tunnel-r630-01:4481af8f-b24c-4cd3-bdd5-f562f4c97df4:r630-01.d-bis.org:https://192.168.11.11:8006"
    ["r630-02"]="tunnel-r630-02:0876f12b-64d7-4927-9ab3-94cb6cf48af9:r630-02.d-bis.org:https://192.168.11.12:8006"
)

# Check if tokens provided
if [ $# -lt 3 ]; then
    log_error "Usage: $0 <ml110-token> <r630-01-token> <r630-02-token>"
    echo ""
    log_info "Example:"
    echo "  $0 \\"
    echo "    'eyJhIjoi...' \\"
    echo "    'eyJhIjoi...' \\"
    echo "    'eyJhIjoi...'"
    echo ""
    log_info "Get tokens from: https://one.dash.cloudflare.com/ → Zero Trust → Networks → Tunnels"
    exit 1
fi

TOKEN_ML110="$1"
TOKEN_R630_01="$2"
TOKEN_R630_02="$3"

declare -A TOKENS=(
    ["ml110"]="$TOKEN_ML110"
    ["r630-01"]="$TOKEN_R630_01"
    ["r630-02"]="$TOKEN_R630_02"
)

log_info "=== Installing All Cloudflare Tunnels ==="
echo ""

# Function to install a tunnel
install_tunnel() {
    local tunnel_key="$1"
    local token="$2"
    IFS=':' read -r tunnel_name tunnel_id hostname target <<< "${TUNNELS[$tunnel_key]}"
    
    log_info "Installing $tunnel_name..."
    
    # Decode token
    if ! TOKEN_DATA=$(echo "$token" | base64 -d 2>/dev/null); then
        log_error "Invalid token format for $tunnel_key"
        return 1
    fi
    
    local account_tag=$(echo "$TOKEN_DATA" | jq -r '.a')
    local tunnel_secret=$(echo "$TOKEN_DATA" | jq -r '.s')
    local token_tunnel_id=$(echo "$TOKEN_DATA" | jq -r '.t')
    
    if [[ "$token_tunnel_id" != "$tunnel_id" ]]; then
        log_warn "Token tunnel ID ($token_tunnel_id) doesn't match expected ($tunnel_id)"
    fi
    
    # Create credentials JSON
    local creds_json=$(jq -n \
        --arg account "$account_tag" \
        --arg secret "$tunnel_secret" \
        --arg id "$tunnel_id" \
        --arg name "$tunnel_name" \
        '{
            AccountTag: $account,
            TunnelSecret: $secret,
            TunnelID: $id,
            TunnelName: $name
        }')
    
    # Create config YAML
    local config_yml="tunnel: $tunnel_id
credentials-file: /etc/cloudflared/credentials-${tunnel_key}.json

ingress:
  - hostname: $hostname
    service: $target
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
  - service: http_status:404"
    
    # Copy files to Proxmox host
    echo "$creds_json" > /tmp/creds-${tunnel_key}.json
    echo "$config_yml" > /tmp/config-${tunnel_key}.yml
    
    scp /tmp/creds-${tunnel_key}.json /tmp/config-${tunnel_key}.yml root@${PROXMOX_HOST}:/tmp/ >/dev/null 2>&1
    
    # Push to container
    ssh root@${PROXMOX_HOST} "pct push $VMID /tmp/creds-${tunnel_key}.json /etc/cloudflared/credentials-${tunnel_key}.json && \
                               pct push $VMID /tmp/config-${tunnel_key}.yml /etc/cloudflared/tunnel-${tunnel_key}.yml && \
                               pct exec $VMID -- chmod 600 /etc/cloudflared/credentials-${tunnel_key}.json && \
                               pct exec $VMID -- mkdir -p /etc/cloudflared" 2>&1 | grep -v "failed to create file" || true
    
    # Install service file
    local service_file="$TUNNELS_DIR/systemd/cloudflared-${tunnel_key}.service"
    if [ -f "$service_file" ]; then
        scp "$service_file" root@${PROXMOX_HOST}:/tmp/ >/dev/null 2>&1
        ssh root@${PROXMOX_HOST} "pct push $VMID /tmp/cloudflared-${tunnel_key}.service /etc/systemd/system/cloudflared-${tunnel_key}.service && \
                                   pct exec $VMID -- systemctl daemon-reload && \
                                   pct exec $VMID -- systemctl enable cloudflared-${tunnel_key}.service" >/dev/null 2>&1
    fi
    
    # Cleanup
    rm -f /tmp/creds-${tunnel_key}.json /tmp/config-${tunnel_key}.yml
    
    log_success "✓ $tunnel_name installed"
}

# Install all tunnels
for tunnel_key in "${!TUNNELS[@]}"; do
    install_tunnel "$tunnel_key" "${TOKENS[$tunnel_key]}"
    echo ""
done

log_success "=== All Tunnels Installed ==="
echo ""
log_info "Starting services..."
ssh root@${PROXMOX_HOST} "pct exec $VMID -- systemctl start cloudflared-ml110 cloudflared-r630-01 cloudflared-r630-02" 2>&1 | grep -v "Unit.*not found" || true

echo ""
log_info "Checking service status..."
ssh root@${PROXMOX_HOST} "pct exec $VMID -- systemctl status cloudflared-* --no-pager | grep -E '(Active|tunnel-|●)' | head -10"

echo ""
log_success "Installation complete!"
log_info "Test URLs:"
log_info "  - https://ml110-01.d-bis.org"
log_info "  - https://r630-01.d-bis.org"
log_info "  - https://r630-02.d-bis.org"

