#!/usr/bin/env bash
# Setup script for Cloudflare Multi-Tunnel configuration
# This script sets up separate tunnels for each Proxmox host

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && 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}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID="${VMID:-102}"
TUNNELS=("ml110" "r630-01" "r630-02")

# Check if running on Proxmox host or need to SSH
if command -v pct &> /dev/null; then
    RUN_LOCAL=true
    log_info "Running on Proxmox host directly"
else
    RUN_LOCAL=false
    log_info "Will execute commands via SSH to $PROXMOX_HOST"
fi

# Function to execute command (local or via SSH)
exec_cmd() {
    if [ "$RUN_LOCAL" = true ]; then
        eval "$@"
    else
        ssh "root@${PROXMOX_HOST}" "$@"
    fi
}

# Function to execute command in container
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 "=== Cloudflare Multi-Tunnel Setup ==="
log_info "Proxmox Host: $PROXMOX_HOST"
log_info "VMID: $VMID"
log_info "Tunnels: ${TUNNELS[*]}"
echo ""

# Check if VMID 102 exists and is running
log_info "Checking VMID $VMID status..."
if ! exec_cmd "pct status $VMID 2>/dev/null | grep -q running"; then
    log_error "VMID $VMID is not running. Please start it first."
    exit 1
fi
log_success "VMID $VMID is running"

# Check if cloudflared is installed
log_info "Checking cloudflared installation..."
if ! exec_in_container "command -v cloudflared &> /dev/null"; then
    log_warn "cloudflared not found. Installing..."
    exec_in_container "
        wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb -O /tmp/cloudflared.deb
        dpkg -i /tmp/cloudflared.deb || apt-get install -f -y
        rm /tmp/cloudflared.deb
        cloudflared --version
    "
    log_success "cloudflared installed"
else
    log_success "cloudflared is installed"
fi

# Create directories
log_info "Creating configuration directories..."
exec_in_container "
    mkdir -p /etc/cloudflared
    mkdir -p /var/log/cloudflared
"
log_success "Directories created"

# Copy configuration files
log_info "Copying configuration files..."
for tunnel in "${TUNNELS[@]}"; do
    config_file="$TUNNELS_DIR/configs/tunnel-${tunnel}.yml"
    
    if [ ! -f "$config_file" ]; then
        log_error "Configuration file not found: $config_file"
        exit 1
    fi
    
    # Copy to container
    if [ "$RUN_LOCAL" = true ]; then
        pct push "$VMID" "$config_file" "/etc/cloudflared/tunnel-${tunnel}.yml"
    else
        scp "$config_file" "root@${PROXMOX_HOST}:/tmp/tunnel-${tunnel}.yml"
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/tunnel-${tunnel}.yml /etc/cloudflared/tunnel-${tunnel}.yml"
    fi
    
    log_success "Copied config for tunnel-${tunnel}"
done

# Copy systemd service files
log_info "Installing systemd service files..."
for tunnel in "${TUNNELS[@]}"; do
    service_file="$TUNNELS_DIR/systemd/cloudflared-${tunnel}.service"
    
    if [ ! -f "$service_file" ]; then
        log_error "Service file not found: $service_file"
        exit 1
    fi
    
    # Copy to container
    if [ "$RUN_LOCAL" = true ]; then
        pct push "$VMID" "$service_file" "/tmp/cloudflared-${tunnel}.service"
        exec_in_container "mv /tmp/cloudflared-${tunnel}.service /etc/systemd/system/cloudflared-${tunnel}.service"
    else
        scp "$service_file" "root@${PROXMOX_HOST}:/tmp/cloudflared-${tunnel}.service"
        ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/cloudflared-${tunnel}.service /etc/systemd/system/cloudflared-${tunnel}.service"
        exec_in_container "mv /tmp/cloudflared-${tunnel}.service /etc/systemd/system/cloudflared-${tunnel}.service"
    fi
    
    log_success "Installed service for tunnel-${tunnel}"
done

# Reload systemd
log_info "Reloading systemd..."
exec_in_container "systemctl daemon-reload"
log_success "Systemd reloaded"

# Prompt for tunnel tokens
log_warn "=== IMPORTANT: Tunnel Setup Required ==="
log_warn "Before enabling services, you need to:"
log_warn "1. Create tunnels in Cloudflare Dashboard"
log_warn "2. Copy tunnel tokens/credentials"
log_warn "3. Update configuration files with tunnel IDs"
log_warn "4. Place credential files in /etc/cloudflared/"
echo ""
log_info "See docs/CLOUDFLARE_ACCESS_SETUP.md for detailed instructions"
echo ""

read -p "Have you created the tunnels and have the credentials ready? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    log_warn "Setup paused. Please create tunnels first."
    log_info "Run this script again after creating tunnels."
    exit 0
fi

# Prompt for each tunnel
for tunnel in "${TUNNELS[@]}"; do
    echo ""
    log_info "=== Setting up tunnel-${tunnel} ==="
    
    read -p "Enter tunnel ID for tunnel-${tunnel}: " tunnel_id
    read -p "Enter path to credentials JSON file (or press Enter to skip): " creds_file
    
    if [ -n "$creds_file" ] && [ -f "$creds_file" ]; then
        # Update config file with tunnel ID
        exec_in_container "sed -i 's/<TUNNEL_ID_${tunnel^^}>/$tunnel_id/g' /etc/cloudflared/tunnel-${tunnel}.yml"
        
        # Copy credentials file
        if [ "$RUN_LOCAL" = true ]; then
            pct push "$VMID" "$creds_file" "/etc/cloudflared/tunnel-${tunnel}.json"
        else
            scp "$creds_file" "root@${PROXMOX_HOST}:/tmp/tunnel-${tunnel}.json"
            ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/tunnel-${tunnel}.json /etc/cloudflared/tunnel-${tunnel}.json"
        fi
        
        exec_in_container "chmod 600 /etc/cloudflared/tunnel-${tunnel}.json"
        log_success "Credentials configured for tunnel-${tunnel}"
    else
        log_warn "Skipping credentials for tunnel-${tunnel}. Configure manually later."
    fi
done

# Enable services (but don't start yet - user should verify configs first)
log_info "Enabling systemd services..."
for tunnel in "${TUNNELS[@]}"; do
    exec_in_container "systemctl enable cloudflared-${tunnel}.service"
    log_success "Enabled cloudflared-${tunnel}.service"
done

echo ""
log_success "=== Setup Complete ==="
log_info "Next steps:"
log_info "1. Verify configuration files in /etc/cloudflared/"
log_info "2. Start services: systemctl start cloudflared-*"
log_info "3. Check status: systemctl status cloudflared-*"
log_info "4. Configure Cloudflare Access (see docs/CLOUDFLARE_ACCESS_SETUP.md)"
log_info "5. Set up monitoring: ./scripts/monitor-tunnels.sh --daemon"

