#!/usr/bin/env bash
# Install cloudflared services using tokens
# This is an alternative to credentials files

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.10}"
VMID="${VMID:-102}"

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"
    ["r630-03"]="tunnel-r630-03:<TUNNEL_ID_R630_03>"
    ["r630-04"]="tunnel-r630-04:<TUNNEL_ID_R630_04>"
)

log_info "=== Cloudflare Tunnel Service Installation ==="
echo ""
log_info "This script will install cloudflared services using tokens"
log_info "You need to provide tokens for each tunnel"
echo ""

# 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
}

# Check if cloudflared is installed
log_info "Checking cloudflared installation..."
if ! exec_in_container "command -v cloudflared >/dev/null 2>&1"; then
    log_error "cloudflared is not installed in VMID $VMID"
    log_info "Install it first:"
    log_info "  ssh root@${PROXMOX_HOST} 'pct exec $VMID -- wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb'"
    log_info "  ssh root@${PROXMOX_HOST} 'pct exec $VMID -- dpkg -i cloudflared-linux-amd64.deb'"
    exit 1
fi
log_success "cloudflared is installed"

echo ""
log_info "For each tunnel, you can either:"
log_info "  1. Provide a token (base64-encoded)"
log_info "  2. Press Enter to skip and configure manually later"
echo ""

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 "Enter token (or press Enter to skip): " token
    
    if [[ -z "$token" ]]; then
        log_warn "Skipping $tunnel_name"
        continue
    fi
    
    # Validate token format (basic check - should be base64)
    if ! echo "$token" | base64 -d >/dev/null 2>&1; then
        log_error "Invalid token format (not base64)"
        continue
    fi
    
    # Decode token to verify
    token_data=$(echo "$token" | base64 -d 2>/dev/null || echo "")
    if ! echo "$token_data" | jq -e '.a, .t' >/dev/null 2>&1; then
        log_error "Invalid token format (not valid JSON)"
        continue
    fi
    
    token_tunnel_id=$(echo "$token_data" | jq -r '.t' 2>/dev/null || echo "")
    if [[ "$token_tunnel_id" != "$tunnel_id" ]]; then
        log_warn "Token tunnel ID ($token_tunnel_id) doesn't match expected ($tunnel_id)"
        read -p "Continue anyway? (y/N): " confirm
        if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
            continue
        fi
    fi
    
    log_info "Installing service for $tunnel_name..."
    
    # Create config file with token
    temp_config=$(mktemp)
    cat > "$temp_config" <<EOF
tunnel: $tunnel_id
credentials-file: /etc/cloudflared/credentials-${tunnel_key}.json

ingress:
EOF
    
    # Add ingress rules based on tunnel
    case "$tunnel_key" in
        "ml110")
            cat >> "$temp_config" <<'INGRESS'
  - hostname: ml110-01.d-bis.org
    service: https://192.168.11.10:8006
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
INGRESS
            ;;
        "r630-01")
            cat >> "$temp_config" <<'INGRESS'
  - hostname: r630-01.d-bis.org
    service: https://192.168.11.11:8006
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
INGRESS
            ;;
        "r630-02")
            cat >> "$temp_config" <<'INGRESS'
  - hostname: r630-02.d-bis.org
    service: https://192.168.11.12:8006
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
INGRESS
            ;;
        "r630-03")
            cat >> "$temp_config" <<'INGRESS'
  - hostname: r630-03.d-bis.org
    service: https://192.168.11.13:8006
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
INGRESS
            ;;
        "r630-04")
            cat >> "$temp_config" <<'INGRESS'
  - hostname: r630-04.d-bis.org
    service: https://192.168.11.14:8006
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
INGRESS
            ;;
    esac
    
    cat >> "$temp_config" <<EOF
  - service: http_status:404
EOF
    
    # Copy config to container
    log_info "  Copying config to VMID $VMID..."
    if [ "$RUN_LOCAL" = true ]; then
        pct push "$VMID" "$temp_config" "/etc/cloudflared/tunnel-${tunnel_key}.yml"
    else
        scp "$temp_config" "root@${PROXMOX_HOST}:/tmp/tunnel-${tunnel_key}.yml" >/dev/null 2>&1
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/tunnel-${tunnel_key}.yml /etc/cloudflared/tunnel-${tunnel_key}.yml" >/dev/null 2>&1
    fi
    
    # Convert token to credentials file format
    token_json=$(echo "$token" | base64 -d | jq -r '{AccountTag: .a, TunnelSecret: .s, TunnelID: .t, TunnelName: "'"$tunnel_name"'"}')
    
    temp_creds=$(mktemp)
    echo "$token_json" > "$temp_creds"
    
    # Copy credentials to container
    log_info "  Copying credentials to VMID $VMID..."
    if [ "$RUN_LOCAL" = true ]; then
        pct push "$VMID" "$temp_creds" "/etc/cloudflared/credentials-${tunnel_key}.json"
    else
        scp "$temp_creds" "root@${PROXMOX_HOST}:/tmp/credentials-${tunnel_key}.json" >/dev/null 2>&1
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/credentials-${tunnel_key}.json /etc/cloudflared/credentials-${tunnel_key}.json" >/dev/null 2>&1
    fi
    
    # Set permissions
    exec_in_container "chmod 600 /etc/cloudflared/credentials-${tunnel_key}.json"
    
    # Update config to use correct credentials path
    exec_in_container "sed -i 's|credentials-file:.*|credentials-file: /etc/cloudflared/credentials-${tunnel_key}.json|g' /etc/cloudflared/tunnel-${tunnel_key}.yml"
    
    # Install systemd service
    log_info "  Installing systemd service..."
    service_file="$TUNNELS_DIR/systemd/cloudflared-${tunnel_key}.service"
    if [ -f "$service_file" ]; then
        if [ "$RUN_LOCAL" = true ]; then
            pct push "$VMID" "$service_file" "/etc/systemd/system/cloudflared-${tunnel_key}.service"
        else
            scp "$service_file" "root@${PROXMOX_HOST}:/tmp/cloudflared-${tunnel_key}.service" >/dev/null 2>&1
            ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/cloudflared-${tunnel_key}.service /etc/systemd/system/cloudflared-${tunnel_key}.service" >/dev/null 2>&1
        fi
        exec_in_container "systemctl daemon-reload"
        exec_in_container "systemctl enable cloudflared-${tunnel_key}.service"
        log_success "  ✓ Service installed and enabled"
    else
        log_warn "  Service file not found: $service_file"
    fi
    
    rm -f "$temp_config" "$temp_creds"
    
    log_success "✓ $tunnel_name configured"
done

echo ""
log_success "=== Installation Complete ==="
log_info "Next steps:"
log_info "1. Start services: ssh root@${PROXMOX_HOST} 'pct exec $VMID -- systemctl start cloudflared-*'"
log_info "2. Check status: ssh root@${PROXMOX_HOST} 'pct exec $VMID -- systemctl status cloudflared-*'"

