#!/bin/bash
# Fix SSL Certificate Error 596 on All Proxmox Host Nodes
# This runs the fix on each Proxmox HOST (not containers)
# Usage: ./scripts/fix-ssl-certificate-all-hosts.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && 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 cluster nodes (HOST nodes, not containers)
declare -A HOSTS
HOSTS[ml110]="192.168.11.10"
HOSTS[r630-01]="192.168.11.11"
HOSTS[r630-02]="192.168.11.12"
HOSTS[r630-03]="192.168.11.13"
HOSTS[r630-04]="192.168.11.14"

fix_host() {
    local host_ip="$1"
    local host_name="${2:-$host_ip}"
    
    log_info "=== Fixing SSL certificates on ${host_name} (${host_ip}) ==="
    echo ""
    
    # Test connectivity
    if ! ping -c 2 -W 2 "$host_ip" >/dev/null 2>&1; then
        log_error "Host ${host_ip} is NOT reachable"
        return 1
    fi
    
    log_info "Running SSL certificate fix on ${host_name}..."
    echo ""
    
    # Execute commands on the Proxmox HOST (not in a container)
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@"$host_ip" bash <<'ENDSSH'
        set -e
        
        echo "Step 1: Regenerating SSL certificates..."
        pvecm updatecerts -f
        echo "✓ Certificates regenerated"
        echo ""
        
        echo "Step 2: Restarting Proxmox services..."
        systemctl restart pveproxy pvedaemon
        sleep 2
        echo "✓ Services restarted"
        echo ""
        
        echo "Step 3: Verifying services..."
        if systemctl is-active --quiet pveproxy && systemctl is-active --quiet pvedaemon; then
            echo "✓ pveproxy: active"
            echo "✓ pvedaemon: active"
        else
            echo "⚠ Some services may not be running properly"
            systemctl status pveproxy --no-pager -l | head -3 || true
            systemctl status pvedaemon --no-pager -l | head -3 || true
        fi
        echo ""
ENDSSH
    
    if [ $? -eq 0 ]; then
        log_success "SSL certificate fix completed for ${host_name}"
    else
        log_error "SSL certificate fix failed for ${host_name}"
        return 1
    fi
    
    echo "----------------------------------------"
    echo ""
}

# Main execution
log_info "Fixing SSL certificates on all Proxmox host nodes..."
echo ""

for host_name in "${!HOSTS[@]}"; do
    host_ip="${HOSTS[$host_name]}"
    fix_host "$host_ip" "$host_name" || log_warn "Failed to fix ${host_name}, continuing..."
done

log_success "All fix attempts complete!"
echo ""
log_info "Next steps:"
log_info "  1. Clear browser cache and cookies"
log_info "  2. Access Proxmox UI: https://<host-ip>:8006"
log_info "  3. Accept certificate warning if prompted"
echo ""
