#!/bin/bash
# Migrate hostnames on Proxmox hosts: pve → r630-01, pve2 → r630-02
# This script properly renames hostnames and updates all necessary configurations

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Load inventory
source "$SCRIPT_DIR/load-physical-inventory.sh" 2>/dev/null || true

# Colors
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"; }

# Hostname mappings
declare -A HOSTNAME_MAP
HOSTNAME_MAP[pve]="r630-01:192.168.11.11:password"
HOSTNAME_MAP[pve2]="r630-02:192.168.11.12:password"

log_section "Proxmox Hostname Migration"

log_warn "This will rename hostnames on Proxmox hosts:"
log_warn "  pve  → r630-01"
log_warn "  pve2 → r630-02"
echo ""

# Auto-confirm if running non-interactively
if [[ -t 0 ]]; then
    read -p "Continue? (yes/no): " confirm
    if [[ "$confirm" != "yes" ]]; then
        log_info "Migration cancelled."
        exit 0
    fi
else
    log_info "Running in non-interactive mode - proceeding with migration..."
fi

migrate_hostname() {
    local old_hostname="$1"
    local new_hostname="${HOSTNAME_MAP[$old_hostname]%%:*}"
    local ip="${HOSTNAME_MAP[$old_hostname]#*:}"
    ip="${ip%%:*}"
    local password="${HOSTNAME_MAP[$old_hostname]##*:}"
    
    log_section "Migrating $old_hostname → $new_hostname (${ip})"
    
    sshpass -p "$password" ssh -o StrictHostKeyChecking=no root@"$ip" bash <<ENDSSH
        set -e
        
        echo "=== Current Configuration ==="
        echo "Current hostname: \$(hostname)"
        echo "IP Address: ${ip}"
        echo ""
        
        # Backup current configuration
        echo "=== Creating Backups ==="
        cp /etc/hostname /etc/hostname.backup.\$(date +%Y%m%d_%H%M%S) 2>/dev/null || true
        cp /etc/hosts /etc/hosts.backup.\$(date +%Y%m%d_%H%M%S) 2>/dev/null || true
        echo "Backups created"
        echo ""
        
        # Stop Proxmox services (if needed for cluster)
        echo "=== Stopping Proxmox Services ==="
        systemctl stop pveproxy pvedaemon pvestatd 2>/dev/null || true
        sleep 2
        echo ""
        
        # Update hostname
        echo "=== Updating Hostname ==="
        echo "$new_hostname" > /etc/hostname
        hostnamectl set-hostname "$new_hostname"
        echo "Hostname set to: $new_hostname"
        echo ""
        
        # Update /etc/hosts
        echo "=== Updating /etc/hosts ==="
        # Remove old entries
        sed -i "/${old_hostname}/d" /etc/hosts
        sed -i "/${ip}/d" /etc/hosts
        
        # Add new entry (hostname must resolve to non-loopback IP)
        echo "${ip}    ${new_hostname} ${new_hostname}.sankofa.nexus ${old_hostname} ${old_hostname}.sankofa.nexus" >> /etc/hosts
        
        echo "Updated /etc/hosts:"
        cat /etc/hosts | grep -E "${ip}|${new_hostname}|${old_hostname}" || true
        echo ""
        
        # Update Proxmox cluster configuration (if in cluster)
        echo "=== Checking Cluster Configuration ==="
        if command -v pvecm >/dev/null 2>&1; then
            cluster_status=\$(pvecm status 2>&1 || echo "not_in_cluster")
            if [[ "\$cluster_status" != "not_in_cluster" ]]; then
                echo "Node is in a cluster. Cluster configuration may need manual update."
                echo "You may need to update cluster configuration after hostname change."
            else
                echo "Node is not in a cluster (standalone)."
            fi
        else
            echo "pvecm not available (not in cluster)."
        fi
        echo ""
        
        # Restart Proxmox services
        echo "=== Restarting Proxmox Services ==="
        systemctl start pvestatd 2>/dev/null || true
        sleep 1
        systemctl start pvedaemon 2>/dev/null || true
        sleep 1
        systemctl start pveproxy 2>/dev/null || true
        sleep 2
        echo ""
        
        # Verify hostname
        echo "=== Verification ==="
        current_hostname=\$(hostname)
        if [[ "\$current_hostname" == "$new_hostname" ]]; then
            echo "✓ Hostname successfully changed to: $new_hostname"
        else
            echo "✗ Hostname change may not have taken effect: \$current_hostname"
        fi
        
        # Verify /etc/hosts resolution
        resolved_ip=\$(getent hosts "$new_hostname" | awk '{print \$1}')
        if [[ "\$resolved_ip" == "${ip}" ]]; then
            echo "✓ Hostname resolves to correct IP: ${ip}"
        else
            echo "✗ Hostname resolution issue: resolves to \$resolved_ip (expected ${ip})"
        fi
        
        # Check services
        echo ""
        echo "Service Status:"
        systemctl is-active pve-cluster >/dev/null && echo "  ✓ pve-cluster: active" || echo "  ✗ pve-cluster: inactive"
        systemctl is-active pvestatd >/dev/null && echo "  ✓ pvestatd: active" || echo "  ✗ pvestatd: inactive"
        systemctl is-active pvedaemon >/dev/null && echo "  ✓ pvedaemon: active" || echo "  ✗ pvedaemon: inactive"
        systemctl is-active pveproxy >/dev/null && echo "  ✓ pveproxy: active" || echo "  ✗ pveproxy: inactive"
        echo ""
ENDSSH
    
    echo ""
    log_info "Testing connectivity with new hostname..."
    sleep 2
    
    # Test SSH with new hostname
    if sshpass -p "$password" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$new_hostname" "echo 'SSH test successful'" 2>/dev/null; then
        log_success "Can connect using new hostname: $new_hostname"
    else
        log_warn "Cannot connect using new hostname (may need DNS update or /etc/hosts on client)"
    fi
    
    # Test SSH with IP
    if sshpass -p "$password" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$ip" "hostname" 2>/dev/null | grep -q "$new_hostname"; then
        log_success "Hostname change verified on host"
    else
        log_warn "Hostname change verification failed"
    fi
    
    log_success "Migration complete for $old_hostname → $new_hostname"
    echo ""
}

# Migrate both hosts
for old_hostname in "${!HOSTNAME_MAP[@]}"; do
    migrate_hostname "$old_hostname"
done

log_section "Migration Summary"

log_success "Hostname migration complete!"
echo ""
log_info "Next steps:"
log_info "1. Update DNS records if using DNS (not just /etc/hosts)"
log_info "2. Update any scripts/configs that reference 'pve' or 'pve2'"
log_info "3. Update cluster configuration if nodes are in a cluster"
log_info "4. Reboot hosts if needed (hostname changes may require reboot for full effect)"
echo ""
log_warn "Note: You may need to update /etc/hosts on other machines to resolve new hostnames"
