#!/usr/bin/env bash
# Save tunnel credentials and update config files after API automation

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TUNNELS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PROJECT_ROOT="$(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"; }

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

declare -A TUNNELS=(
    ["ml110"]="tunnel-ml110"
    ["r630-01"]="tunnel-r630-01"
    ["r630-02"]="tunnel-r630-02"
)

# Usage
if [ $# -lt 2 ]; then
    echo "Usage: $0 <tunnel-name> <tunnel-id> <tunnel-token>"
    echo ""
    echo "Example:"
    echo "  $0 ml110 abc123def456 'eyJhIjoi...'"
    exit 1
fi

TUNNEL_NAME="$1"
TUNNEL_ID="$2"
TUNNEL_TOKEN="$3"

if [[ ! "$TUNNEL_NAME" =~ ^(ml110|r630-01|r630-02)$ ]]; then
    log_error "Invalid tunnel name: $TUNNEL_NAME"
    exit 1
fi

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

log_info "Saving credentials for tunnel: $TUNNEL_NAME"

# Create credentials JSON
temp_creds=$(mktemp)
cat > "$temp_creds" <<EOF
{
  "AccountTag": "${CLOUDFLARE_ACCOUNT_ID:-}",
  "TunnelSecret": "${TUNNEL_TOKEN}",
  "TunnelID": "${TUNNEL_ID}",
  "TunnelName": "${TUNNELS[$TUNNEL_NAME]}"
}
EOF

# Copy to container
log_info "Copying credentials to VMID $VMID..."
if [ "$RUN_LOCAL" = true ]; then
    pct push "$VMID" "$temp_creds" "/etc/cloudflared/tunnel-${TUNNEL_NAME}.json"
else
    scp "$temp_creds" "root@${PROXMOX_HOST}:/tmp/tunnel-${TUNNEL_NAME}.json"
    ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/tunnel-${TUNNEL_NAME}.json /etc/cloudflared/tunnel-${TUNNEL_NAME}.json"
fi

# Set permissions
exec_in_container "chmod 600 /etc/cloudflared/tunnel-${TUNNEL_NAME}.json"
log_success "Credentials saved"

# Update config file with tunnel ID
log_info "Updating config file with tunnel ID..."
config_file="$TUNNELS_DIR/configs/tunnel-${TUNNEL_NAME}.yml"

if [ -f "$config_file" ]; then
    # Update tunnel ID in config
    if [ "$RUN_LOCAL" = true ]; then
        sed -i "s/<TUNNEL_ID_${TUNNEL_NAME^^}>/$TUNNEL_ID/g" "$config_file"
        pct push "$VMID" "$config_file" "/etc/cloudflared/tunnel-${TUNNEL_NAME}.yml"
    else
        sed "s/<TUNNEL_ID_${TUNNEL_NAME^^}>/$TUNNEL_ID/g" "$config_file" > "/tmp/tunnel-${TUNNEL_NAME}.yml"
        scp "/tmp/tunnel-${TUNNEL_NAME}.yml" "root@${PROXMOX_HOST}:/tmp/"
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/tunnel-${TUNNEL_NAME}.yml /etc/cloudflared/tunnel-${TUNNEL_NAME}.yml"
    fi
    log_success "Config file updated"
else
    log_warn "Config file not found: $config_file"
fi

# Cleanup
rm -f "$temp_creds"

log_success "Credentials and config saved for tunnel-${TUNNEL_NAME}"

