#!/usr/bin/env bash
# One-time health check for all Cloudflare tunnels

set -euo pipefail

# 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}"
TUNNELS=("ml110" "r630-01" "r630-02" "r630-03" "r630-04")

declare -A TUNNEL_DOMAINS=(
    ["ml110"]="ml110-01.d-bis.org"
    ["r630-01"]="r630-01.d-bis.org"
    ["r630-02"]="r630-02.d-bis.org"
    ["r630-03"]="r630-03.d-bis.org"
    ["r630-04"]="r630-04.d-bis.org"
)

declare -A TUNNEL_IPS=(
    ["ml110"]="192.168.11.10"
    ["r630-01"]="192.168.11.11"
    ["r630-02"]="192.168.11.12"
    ["r630-03"]="192.168.11.13"
    ["r630-04"]="192.168.11.14"
)

# 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 service status
check_service() {
    local tunnel="$1"
    local service="cloudflared-${tunnel}"
    
    if exec_in_container "systemctl is-active --quiet $service 2>/dev/null"; then
        return 0
    fi
    return 1
}

# Check service logs for errors
check_logs() {
    local tunnel="$1"
    local service="cloudflared-${tunnel}"
    
    # Check for recent errors in logs
    if exec_in_container "journalctl -u $service --since '5 minutes ago' --no-pager | grep -i error | head -1"; then
        return 1
    fi
    return 0
}

# Check DNS resolution
check_dns() {
    local domain="$1"
    
    if dig +short "$domain" | grep -q .; then
        return 0
    fi
    return 1
}

# Check HTTPS connectivity
check_https() {
    local domain="$1"
    local http_code
    
    http_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://${domain}" 2>/dev/null || echo "000")
    
    if [[ "$http_code" =~ ^(200|302|403|401)$ ]]; then
        return 0
    fi
    return 1
}

# Check internal connectivity
check_internal() {
    local ip="$1"
    local port="${2:-8006}"
    
    if timeout 5 bash -c "echo > /dev/tcp/${ip}/${port}" 2>/dev/null; then
        return 0
    fi
    return 1
}

# Print header
echo ""
echo "=========================================="
echo "  Cloudflare Tunnel Health Check"
echo "=========================================="
echo ""

# Check each tunnel
for tunnel in "${TUNNELS[@]}"; do
    domain="${TUNNEL_DOMAINS[$tunnel]}"
    ip="${TUNNEL_IPS[$tunnel]}"
    service="cloudflared-${tunnel}"
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Tunnel: $tunnel ($domain)"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Check service status
    if check_service "$tunnel"; then
        log_success "Service is running"
    else
        log_error "Service is NOT running"
        echo ""
        continue
    fi
    
    # Check logs
    if check_logs "$tunnel"; then
        log_success "No recent errors in logs"
    else
        log_warn "Recent errors found in logs"
        exec_in_container "journalctl -u $service --since '5 minutes ago' --no-pager | grep -i error | head -3"
    fi
    
    # Check DNS
    if check_dns "$domain"; then
        log_success "DNS resolution: OK"
        dig +short "$domain" | head -1 | sed 's/^/  → /'
    else
        log_error "DNS resolution: FAILED"
    fi
    
    # Check HTTPS connectivity
    if check_https "$domain"; then
        log_success "HTTPS connectivity: OK"
    else
        log_error "HTTPS connectivity: FAILED"
    fi
    
    # Check internal connectivity
    if check_internal "$ip" 8006; then
        log_success "Internal connectivity to $ip:8006: OK"
    else
        log_error "Internal connectivity to $ip:8006: FAILED"
    fi
    
    # Get service uptime
    uptime=$(exec_in_container "systemctl show $service --property=ActiveEnterTimestamp --value 2>/dev/null" || echo "unknown")
    if [ "$uptime" != "unknown" ]; then
        log_info "Service started: $uptime"
    fi
    
    echo ""
done

# Summary
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Summary"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

all_healthy=true
for tunnel in "${TUNNELS[@]}"; do
    if ! check_service "$tunnel"; then
        all_healthy=false
        break
    fi
done

if [ "$all_healthy" = true ]; then
    log_success "All tunnels are healthy"
else
    log_error "Some tunnels are not healthy"
fi

echo ""

