#!/usr/bin/env bash
# Automated credentials setup - checks for files and sets up everything

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"
)

# 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")" >/dev/null 2>&1
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/$(basename "$src") $dst" >/dev/null 2>&1
    fi
}

log_info "=== Automated Credentials Setup ==="
echo ""

# Check for credentials files in current directory
MISSING_FILES=()
FOUND_FILES=()

for tunnel_key in "${!TUNNELS[@]}"; do
    IFS=':' read -r tunnel_name tunnel_id <<< "${TUNNELS[$tunnel_key]}"
    
    # Try multiple possible file names
    creds_file=""
    for possible_name in "credentials-${tunnel_key}.json" "credentials-${tunnel_name}.json" "${tunnel_name}.json"; do
        if [ -f "$TUNNELS_DIR/$possible_name" ]; then
            creds_file="$TUNNELS_DIR/$possible_name"
            break
        fi
        if [ -f "$possible_name" ]; then
            creds_file="$possible_name"
            break
        fi
    done
    
    if [[ -n "$creds_file" ]] && [[ -f "$creds_file" ]]; then
        FOUND_FILES+=("$tunnel_key:$creds_file")
        log_success "Found credentials for $tunnel_name: $creds_file"
    else
        MISSING_FILES+=("$tunnel_key:$tunnel_name:$tunnel_id")
        log_warn "Missing credentials for $tunnel_name"
    fi
done

echo ""

# If some files are missing, provide instructions
if [ ${#MISSING_FILES[@]} -gt 0 ]; then
    log_error "Missing credentials files:"
    for entry in "${MISSING_FILES[@]}"; do
        IFS=':' read -r key name id <<< "$entry"
        echo "  - $name (ID: $id)"
    done
    echo ""
    log_info "To download credentials:"
    echo "  1. Go to: https://one.dash.cloudflare.com/ → Zero Trust → Networks → Tunnels"
    echo "  2. Click each tunnel → Configure → Download credentials file"
    echo "  3. Save as: credentials-${key}.json in $TUNNELS_DIR"
    echo "  4. Run this script again"
    echo ""
    
    if [ ${#FOUND_FILES[@]} -eq 0 ]; then
        log_error "No credentials files found. Cannot proceed."
        exit 1
    else
        log_warn "Proceeding with available credentials only..."
        echo ""
    fi
fi

# Process found files
if [ ${#FOUND_FILES[@]} -eq 0 ]; then
    log_error "No credentials files found!"
    exit 1
fi

log_info "Setting up credentials for ${#FOUND_FILES[@]} tunnel(s)..."
echo ""

# Ensure /etc/cloudflared exists in container
exec_in_container "mkdir -p /etc/cloudflared"

for entry in "${FOUND_FILES[@]}"; do
    IFS=':' read -r tunnel_key creds_file <<< "$entry"
    IFS=':' read -r tunnel_name tunnel_id <<< "${TUNNELS[$tunnel_key]}"
    
    log_info "Processing $tunnel_name..."
    
    # Validate JSON structure
    if ! jq -e '.AccountTag, .TunnelSecret, .TunnelID' "$creds_file" >/dev/null 2>&1; then
        log_error "Invalid credentials file format: $creds_file"
        log_info "Expected format: { \"AccountTag\": \"...\", \"TunnelSecret\": \"...\", \"TunnelID\": \"...\" }"
        continue
    fi
    
    # Copy credentials to container
    log_info "  Copying credentials to VMID $VMID..."
    copy_to_container "$creds_file" "/etc/cloudflared/credentials-${tunnel_key}.json"
    
    # Set permissions
    exec_in_container "chmod 600 /etc/cloudflared/credentials-${tunnel_key}.json"
    
    # Update config file
    config_file="$TUNNELS_DIR/configs/tunnel-${tunnel_key}.yml"
    if [ -f "$config_file" ]; then
        log_info "  Updating config file..."
        temp_config=$(mktemp)
        
        # Replace tunnel ID placeholder
        sed "s/<TUNNEL_ID_${tunnel_key^^}>/$tunnel_id/g" "$config_file" > "$temp_config"
        
        # Ensure credentials path is correct
        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 "  ✓ $tunnel_name configured"
    else
        log_warn "  Config file not found: $config_file"
    fi
    
    echo ""
done

log_success "=== Setup Complete ==="
echo ""
log_info "Next steps:"
log_info "1. Verify: 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-*'"
log_info "4. Enable on boot: ssh root@${PROXMOX_HOST} 'pct exec $VMID -- systemctl enable cloudflared-*'"

