#!/usr/bin/env bash
# Generate credentials files for existing Cloudflare Tunnels
# This script helps create the credentials JSON files needed for existing tunnels

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 account ID from .env if available
if [ -f "$TUNNELS_DIR/../../.env" ]; then
    source "$TUNNELS_DIR/../../.env" 2>/dev/null || true
fi

declare -A TUNNELS=(
    ["ml110"]="tunnel-ml110:ccd7150a-9881-4b8c-a105-9b4ead6e69a2"
    ["r630-01"]="tunnel-r630-01:4481af8f-b24c-4cd3-bdd5-f562f4c97df4"
    ["r630-02"]="tunnel-r630-02:0876f12b-64d7-4927-9ab3-94cb6cf48af9"
)

log_info "=== Cloudflare Tunnel Credentials Generator ==="
echo ""
log_info "For existing tunnels, you have two options:"
echo ""
echo "Option 1: Download from Cloudflare Dashboard (Recommended)"
echo "  1. Go to: https://one.dash.cloudflare.com/"
echo "  2. Navigate to: Zero Trust > Networks > Tunnels"
echo "  3. Click on each tunnel"
echo "  4. Click 'Configure' > 'Local Management' > 'Download credentials file'"
echo "  5. Save as: credentials-<tunnel-name>.json"
echo ""
echo "Option 2: Use cloudflared CLI (if you have access)"
echo "  Run: cloudflared tunnel create <tunnel-name>"
echo "  This will generate credentials for a new tunnel with that name"
echo "  (Note: This creates a NEW tunnel, not for existing ones)"
echo ""
read -p "Do you have credentials files ready? (y/n): " has_creds

if [[ "$has_creds" != "y" && "$has_creds" != "Y" ]]; then
    log_warn "Please download credentials from Cloudflare Dashboard first"
    log_info "See: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#download-the-credentials-file"
    exit 0
fi

log_info ""
log_info "For each tunnel, provide the path to the credentials JSON file"
log_info "Or press Enter to skip and configure manually later"
echo ""

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

# Check if running on Proxmox host
if command -v pct &> /dev/null; then
    RUN_LOCAL=true
else
    RUN_LOCAL=false
fi

exec_in_container() {
    local cmd="$1"
    if [ "$RUN_LOCAL" = true ]; then
        pct exec "$VMID" -- bash -c "$cmd"
    else
        ssh "root@${PROXMOX_HOST}" "pct exec $VMID -- bash -c '$cmd'"
    fi
}

copy_to_container() {
    local src="$1"
    local dst="$2"
    if [ "$RUN_LOCAL" = true ]; then
        pct push "$VMID" "$src" "$dst"
    else
        scp "$src" "root@${PROXMOX_HOST}:/tmp/$(basename "$src")"
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/$(basename "$src") $dst"
    fi
}

for tunnel_key in "${!TUNNELS[@]}"; do
    IFS=':' read -r tunnel_name tunnel_id <<< "${TUNNELS[$tunnel_key]}"
    
    echo ""
    log_info "=== Tunnel: $tunnel_name (ID: $tunnel_id) ==="
    read -p "Path to credentials JSON file (or Enter to skip): " creds_path
    
    if [[ -z "$creds_path" ]]; then
        log_warn "Skipping $tunnel_name"
        continue
    fi
    
    if [[ ! -f "$creds_path" ]]; then
        log_error "File not found: $creds_path"
        continue
    fi
    
    # Validate JSON structure
    if ! jq -e '.AccountTag, .TunnelSecret, .TunnelID' "$creds_path" >/dev/null 2>&1; then
        log_error "Invalid credentials file format"
        log_info "Expected format:"
        log_info '  {'
        log_info '    "AccountTag": "...",'
        log_info '    "TunnelSecret": "...",'
        log_info '    "TunnelID": "...",'
        log_info '    "TunnelName": "..."'
        log_info '  }'
        continue
    fi
    
    # Copy to container
    log_info "Copying credentials to VMID $VMID..."
    copy_to_container "$creds_path" "/etc/cloudflared/credentials-${tunnel_key}.json"
    
    # Set permissions
    exec_in_container "chmod 600 /etc/cloudflared/credentials-${tunnel_key}.json"
    
    # Update config file to use correct credentials path
    config_file="$TUNNELS_DIR/configs/tunnel-${tunnel_key}.yml"
    if [ -f "$config_file" ]; then
        # Update tunnel ID in config
        temp_config=$(mktemp)
        sed "s/<TUNNEL_ID_${tunnel_key^^}>/$tunnel_id/g" "$config_file" > "$temp_config"
        sed -i "s|credentials-file:.*|credentials-file: /etc/cloudflared/credentials-${tunnel_key}.json|g" "$temp_config"
        
        # Copy config to container
        copy_to_container "$temp_config" "/etc/cloudflared/tunnel-${tunnel_key}.yml"
        rm -f "$temp_config"
        
        log_success "Credentials and config saved for $tunnel_name"
    else
        log_warn "Config file not found: $config_file"
    fi
done

echo ""
log_success "=== Credentials Setup Complete ==="
log_info "Next steps:"
log_info "1. Verify configs: ssh root@${PROXMOX_HOST} 'pct exec $VMID -- ls -la /etc/cloudflared/'"
log_info "2. Start services: ssh root@${PROXMOX_HOST} 'pct exec $VMID -- systemctl start cloudflared-*'"
log_info "3. Check status: ssh root@${PROXMOX_HOST} 'pct exec $VMID -- systemctl status cloudflared-*'"

