#!/bin/bash
# Fix Cluster Node Names - Update corosync.conf to match system hostnames
# Changes: pve -> r630-01, pve2 -> r630-02

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/load-physical-inventory.sh" 2>/dev/null || true

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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"; }
log_section() { echo -e "\n${CYAN}=== $1 ===${NC}\n"; }

ML110_IP="${PROXMOX_HOST_ML110:-192.168.11.10}"
ML110_PASS="${PROXMOX_PASS_ML110:-L@kers2010}"

log_section "Fix Cluster Node Names"

log_warn "This will update cluster node names in corosync.conf:"
log_warn "  pve  -> r630-01"
log_warn "  pve2 -> r630-02"
echo ""

read -p "Continue? (yes/no): " confirm
if [[ "$confirm" != "yes" ]]; then
    log_info "Operation cancelled."
    exit 0
fi

log_section "Backing up corosync.conf"

sshpass -p "$ML110_PASS" ssh -o StrictHostKeyChecking=no root@"$ML110_IP" bash <<'ENDSSH'
    # Backup corosync.conf
    cp /etc/pve/corosync.conf /etc/pve/corosync.conf.backup.$(date +%Y%m%d_%H%M%S)
    echo "Backup created"
ENDSSH

log_section "Updating corosync.conf"

sshpass -p "$ML110_PASS" ssh -o StrictHostKeyChecking=no root@"$ML110_IP" bash <<'ENDSSH'
    # Read current config version
    CURRENT_VERSION=$(grep "config_version:" /etc/pve/corosync.conf | awk '{print $2}')
    NEW_VERSION=$((CURRENT_VERSION + 1))
    
    echo "Current config version: $CURRENT_VERSION"
    echo "New config version: $NEW_VERSION"
    
    # Update corosync.conf
    sed -i 's/name: pve$/name: r630-01/' /etc/pve/corosync.conf
    sed -i 's/name: pve2$/name: r630-02/' /etc/pve/corosync.conf
    sed -i "s/config_version: $CURRENT_VERSION/config_version: $NEW_VERSION/" /etc/pve/corosync.conf
    
    echo ""
    echo "Updated corosync.conf:"
    cat /etc/pve/corosync.conf
ENDSSH

log_section "Renaming node directories"

# Rename node directories (must be done on each node)
for node in "r630-01:192.168.11.11:password" "r630-02:192.168.11.12:password"; do
    IFS=: read -r new_name ip pass <<< "$node"
    old_name="pve"
    if [[ "$new_name" == "r630-02" ]]; then
        old_name="pve2"
    fi
    
    log_info "Renaming node directory on $new_name ($ip): $old_name -> $new_name"
    
    sshpass -p "$pass" ssh -o StrictHostKeyChecking=no root@"$ip" bash <<ENDSSH
        # Check if old directory exists
        if [ -d "/etc/pve/nodes/$old_name" ]; then
            # Rename directory
            mv /etc/pve/nodes/$old_name /etc/pve/nodes/$new_name
            echo "Renamed /etc/pve/nodes/$old_name -> /etc/pve/nodes/$new_name"
        else
            echo "Directory /etc/pve/nodes/$old_name does not exist (may already be renamed)"
        fi
ENDSSH
done

log_section "Reloading cluster configuration"

# Reload corosync on all nodes
for node in "ml110:192.168.11.10:L@kers2010" "r630-01:192.168.11.11:password" "r630-02:192.168.11.12:password"; do
    IFS=: read -r name ip pass <<< "$node"
    log_info "Reloading corosync on $name ($ip)"
    
    sshpass -p "$pass" ssh -o StrictHostKeyChecking=no root@"$ip" \
        "systemctl reload corosync 2>&1 || systemctl restart corosync 2>&1" 2>/dev/null || true
done

log_section "Verification"

log_info "Checking cluster status..."
sshpass -p "$ML110_PASS" ssh -o StrictHostKeyChecking=no root@"$ML110_IP" bash <<'ENDSSH'
    echo "=== Cluster Nodes ==="
    pvecm nodes 2>/dev/null || echo "pvecm nodes failed"
    echo ""
    echo "=== Cluster Status ==="
    pvecm status 2>/dev/null | head -20 || echo "pvecm status failed"
ENDSSH

log_section "Fix Complete"
log_success "Cluster node names updated!"
log_info "Verification: Run 'pvecm nodes' to verify new node names"
