#!/usr/bin/env bash
# Install and configure a single Cloudflare tunnel

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}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Usage
if [ $# -lt 1 ]; then
    echo "Usage: $0 <tunnel-name> [tunnel-id] [credentials-file]"
    echo ""
    echo "Tunnel names: ml110, r630-01, r630-02"
    echo ""
    echo "Example:"
    echo "  $0 ml110"
    echo "  $0 ml110 abc123def456 /path/to/credentials.json"
    exit 1
fi

TUNNEL_NAME="$1"
TUNNEL_ID="${2:-}"
CREDS_FILE="${3:-}"

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

# Validate tunnel name
if [[ ! "$TUNNEL_NAME" =~ ^(ml110|r630-01|r630-02)$ ]]; then
    log_error "Invalid tunnel name: $TUNNEL_NAME"
    log_error "Valid names: ml110, r630-01, r630-02"
    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 "Installing tunnel: $TUNNEL_NAME"

# Check VMID
if ! exec_in_container "true"; then
    log_error "Cannot access VMID $VMID"
    exit 1
fi

# Copy config file
config_file="$TUNNELS_DIR/configs/tunnel-${TUNNEL_NAME}.yml"
if [ ! -f "$config_file" ]; then
    log_error "Configuration file not found: $config_file"
    exit 1
fi

log_info "Copying configuration file..."
if [ "$RUN_LOCAL" = true ]; then
    pct push "$VMID" "$config_file" "/etc/cloudflared/tunnel-${TUNNEL_NAME}.yml"
else
    scp "$config_file" "root@${PROXMOX_HOST}:/tmp/tunnel-${TUNNEL_NAME}.yml"
    ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/tunnel-${TUNNEL_NAME}.yml /etc/cloudflared/tunnel-${TUNNEL_NAME}.yml"
fi

# Update tunnel ID if provided
if [ -n "$TUNNEL_ID" ]; then
    log_info "Updating tunnel ID..."
    exec_in_container "sed -i 's/<TUNNEL_ID_${TUNNEL_NAME^^}>/$TUNNEL_ID/g' /etc/cloudflared/tunnel-${TUNNEL_NAME}.yml"
    log_success "Tunnel ID updated"
fi

# Copy credentials if provided
if [ -n "$CREDS_FILE" ] && [ -f "$CREDS_FILE" ]; then
    log_info "Copying credentials file..."
    if [ "$RUN_LOCAL" = true ]; then
        pct push "$VMID" "$CREDS_FILE" "/etc/cloudflared/tunnel-${TUNNEL_NAME}.json"
    else
        scp "$CREDS_FILE" "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
    exec_in_container "chmod 600 /etc/cloudflared/tunnel-${TUNNEL_NAME}.json"
    log_success "Credentials file copied"
fi

# Install systemd service
service_file="$TUNNELS_DIR/systemd/cloudflared-${TUNNEL_NAME}.service"
if [ ! -f "$service_file" ]; then
    log_error "Service file not found: $service_file"
    exit 1
fi

log_info "Installing systemd service..."
if [ "$RUN_LOCAL" = true ]; then
    pct push "$VMID" "$service_file" "/tmp/cloudflared-${TUNNEL_NAME}.service"
    exec_in_container "mv /tmp/cloudflared-${TUNNEL_NAME}.service /etc/systemd/system/cloudflared-${TUNNEL_NAME}.service"
else
    scp "$service_file" "root@${PROXMOX_HOST}:/tmp/cloudflared-${TUNNEL_NAME}.service"
    ssh "root@${PROXMOX_HOST}" "pct push $VMID /tmp/cloudflared-${TUNNEL_NAME}.service /etc/systemd/system/cloudflared-${TUNNEL_NAME}.service"
    exec_in_container "mv /tmp/cloudflared-${TUNNEL_NAME}.service /etc/systemd/system/cloudflared-${TUNNEL_NAME}.service"
fi

# Reload systemd
exec_in_container "systemctl daemon-reload"
exec_in_container "systemctl enable cloudflared-${TUNNEL_NAME}.service"

log_success "Tunnel $TUNNEL_NAME installed and enabled"
log_info "Start with: systemctl start cloudflared-${TUNNEL_NAME}.service"

