#!/bin/bash
# create-proxmox-cluster-ssh.sh
# Creates a Proxmox cluster using SSH access to nodes

set -euo pipefail

# Load environment variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "${SCRIPT_DIR}/../.env" ]; then
    set -a
    source <(grep -v '^#' "${SCRIPT_DIR}/../.env" | grep -v '^$' | sed 's/^/export /')
    set +a
fi

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Configuration
CLUSTER_NAME="${CLUSTER_NAME:-sankofa-cluster}"
NODE1_IP="192.168.11.10"
NODE1_NAME="ML110-01"
NODE2_IP="192.168.11.11"
NODE2_NAME="R630-01"

# SSH configuration (if available)
SSH_USER="${SSH_USER:-root}"
SSH_KEY="${SSH_KEY:-}"

log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

check_ssh_access() {
    log "Checking SSH access to nodes..."
    
    local ssh_cmd="ssh"
    if [ -n "$SSH_KEY" ]; then
        ssh_cmd="ssh -i $SSH_KEY"
    fi
    
    # Test Node 1
    if $ssh_cmd -o ConnectTimeout=5 -o StrictHostKeyChecking=no ${SSH_USER}@${NODE1_IP} "echo 'Connected'" >/dev/null 2>&1; then
        log "✓ SSH access to ${NODE1_IP} working"
    else
        error "SSH access to ${NODE1_IP} failed. Please ensure SSH is configured."
    fi
    
    # Test Node 2
    if $ssh_cmd -o ConnectTimeout=5 -o StrictHostKeyChecking=no ${SSH_USER}@${NODE2_IP} "echo 'Connected'" >/dev/null 2>&1; then
        log "✓ SSH access to ${NODE2_IP} working"
    else
        error "SSH access to ${NODE2_IP} failed. Please ensure SSH is configured."
    fi
}

create_cluster_node1() {
    log "Creating cluster on ${NODE1_NAME}..."
    
    local ssh_cmd="ssh"
    if [ -n "$SSH_KEY" ]; then
        ssh_cmd="ssh -i $SSH_KEY"
    fi
    
    # Check if already in cluster
    local cluster_status=$($ssh_cmd ${SSH_USER}@${NODE1_IP} "pvecm status 2>/dev/null || echo 'not-in-cluster'")
    
    if echo "$cluster_status" | grep -q "Cluster name"; then
        warn "${NODE1_NAME} is already in a cluster"
        echo "$cluster_status"
        return 1
    fi
    
    # Create cluster
    log "Creating cluster '${CLUSTER_NAME}'..."
    $ssh_cmd ${SSH_USER}@${NODE1_IP} "pvecm create ${CLUSTER_NAME}" || {
        error "Failed to create cluster on ${NODE1_NAME}"
    }
    
    log "✓ Cluster created on ${NODE1_NAME}"
    
    # Verify
    $ssh_cmd ${SSH_USER}@${NODE1_IP} "pvecm status"
}

add_node2_to_cluster() {
    log "Adding ${NODE2_NAME} to cluster..."
    
    local ssh_cmd="ssh"
    if [ -n "$SSH_KEY" ]; then
        ssh_cmd="ssh -i $SSH_KEY"
    fi
    
    # Check if already in cluster
    local cluster_status=$($ssh_cmd ${SSH_USER}@${NODE2_IP} "pvecm status 2>/dev/null || echo 'not-in-cluster'")
    
    if echo "$cluster_status" | grep -q "Cluster name"; then
        warn "${NODE2_NAME} is already in a cluster"
        echo "$cluster_status"
        return 1
    fi
    
    # Add to cluster
    log "Joining ${NODE2_NAME} to cluster..."
    $ssh_cmd ${SSH_USER}@${NODE2_IP} "pvecm add ${NODE1_IP}" || {
        error "Failed to add ${NODE2_NAME} to cluster"
    }
    
    log "✓ ${NODE2_NAME} added to cluster"
    
    # Verify
    $ssh_cmd ${SSH_USER}@${NODE2_IP} "pvecm status"
}

configure_quorum() {
    log "Configuring quorum for 2-node cluster..."
    
    local ssh_cmd="ssh"
    if [ -n "$SSH_KEY" ]; then
        ssh_cmd="ssh -i $SSH_KEY"
    fi
    
    # Set expected votes to 2
    $ssh_cmd ${SSH_USER}@${NODE1_IP} "pvecm expected 2" || {
        warn "Failed to set expected votes on ${NODE1_NAME}"
    }
    
    $ssh_cmd ${SSH_USER}@${NODE2_IP} "pvecm expected 2" || {
        warn "Failed to set expected votes on ${NODE2_NAME}"
    }
    
    log "✓ Quorum configured"
}

verify_cluster() {
    log "Verifying cluster status..."
    
    local ssh_cmd="ssh"
    if [ -n "$SSH_KEY" ]; then
        ssh_cmd="ssh -i $SSH_KEY"
    fi
    
    echo ""
    info "Cluster status on ${NODE1_NAME}:"
    $ssh_cmd ${SSH_USER}@${NODE1_IP} "pvecm status && echo '' && pvecm nodes"
    
    echo ""
    info "Cluster status on ${NODE2_NAME}:"
    $ssh_cmd ${SSH_USER}@${NODE2_IP} "pvecm status && echo '' && pvecm nodes"
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║     Proxmox Cluster Creation (SSH Method)                  ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    
    check_ssh_access
    echo ""
    
    info "Cluster Configuration:"
    echo "  Cluster Name: ${CLUSTER_NAME}"
    echo "  Node 1: ${NODE1_NAME} (${NODE1_IP})"
    echo "  Node 2: ${NODE2_NAME} (${NODE2_IP})"
    echo ""
    
    read -p "Create cluster? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log "Cluster creation cancelled"
        exit 0
    fi
    echo ""
    
    # Create cluster on node 1
    if create_cluster_node1; then
        log "Cluster created successfully"
    else
        error "Failed to create cluster"
    fi
    echo ""
    
    # Add node 2
    if add_node2_to_cluster; then
        log "Node 2 added successfully"
    else
        error "Failed to add node 2"
    fi
    echo ""
    
    # Configure quorum
    configure_quorum
    echo ""
    
    # Verify
    verify_cluster
    echo ""
    
    log "✓ Cluster creation complete!"
    echo ""
    info "Next steps:"
    info "1. Verify cluster in Proxmox web UI"
    info "2. Test VM creation and migration"
    info "3. Configure shared storage (if needed)"
}

main "$@"

