#!/bin/bash
# setup-ssh-with-password.sh
# Sets up SSH access using password from .env file

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'

SSH_KEY="${SSH_KEY:-$HOME/.ssh/sankofa_proxmox}"
NODE1_IP="192.168.11.10"
NODE2_IP="192.168.11.11"
PROXMOX_PASSWORD="${PROXMOX_ROOT_PASS:-${PROXMOX_PASSWORD:-}}"

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

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

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

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

check_password() {
    if [ -z "$PROXMOX_PASSWORD" ]; then
        warn "PROXMOX_ROOT_PASS or PROXMOX_PASSWORD not set in .env file"
        info "Add to .env: PROXMOX_ROOT_PASS=your-root-password"
        return 1
    fi
    return 0
}

copy_key_with_password() {
    local node_ip=$1
    local node_name=$2
    
    info "Copying SSH key to ${node_name} using password..."
    
    if [ -z "$PROXMOX_PASSWORD" ]; then
        error "Password not available - cannot copy key automatically"
        return 1
    fi
    
    # Use sshpass if available, or expect, or manual
    if command -v sshpass &> /dev/null; then
        if sshpass -p "$PROXMOX_PASSWORD" ssh-copy-id -i "$SSH_KEY.pub" -o StrictHostKeyChecking=no root@"${node_ip}" 2>/dev/null; then
            log "SSH key copied to ${node_name} using sshpass"
            return 0
        else
            error "Failed to copy key to ${node_name}"
            return 1
        fi
    else
        warn "sshpass not installed - cannot automate password-based key copy"
        info "Install sshpass: sudo apt-get install sshpass"
        info "Or copy manually: ssh-copy-id -i $SSH_KEY.pub root@${node_ip}"
        return 1
    fi
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║          SSH Setup with Password from .env                  ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    
    # Check for password
    if ! check_password; then
        echo ""
        info "To use this script, add to .env file:"
        echo "  PROXMOX_PASSWORD=your-root-password-here"
        echo ""
        info "Alternatively, use manual SSH key copy:"
        echo "  ssh-copy-id -i $SSH_KEY.pub root@192.168.11.10"
        echo "  ssh-copy-id -i $SSH_KEY.pub root@192.168.11.11"
        echo ""
        return 1
    fi
    
    # Check for SSH key
    if [ ! -f "$SSH_KEY" ]; then
        info "Generating SSH key..."
        ssh-keygen -t ed25519 -C "sankofa-proxmox" -f "$SSH_KEY" -N "" -q
        log "SSH key generated: $SSH_KEY"
    else
        log "SSH key exists: $SSH_KEY"
    fi
    
    # Check for sshpass
    if ! command -v sshpass &> /dev/null; then
        warn "sshpass not installed"
        info "Install with: sudo apt-get install sshpass"
        info "Or use manual key copy (will prompt for password)"
        echo ""
    fi
    
    # Copy keys
    copy_key_with_password "$NODE1_IP" "ML110-01"
    copy_key_with_password "$NODE2_IP" "R630-01"
    
    # Test connections
    echo ""
    info "Testing SSH connections..."
    if ssh -i "$SSH_KEY" -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"${NODE1_IP}" 'hostname' &> /dev/null; then
        log "SSH to ML110-01 works!"
    else
        warn "SSH to ML110-01 failed"
    fi
    
    if ssh -i "$SSH_KEY" -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"${NODE2_IP}" 'hostname' &> /dev/null; then
        log "SSH to R630-01 works!"
    else
        warn "SSH to R630-01 failed"
    fi
    
    echo ""
}

main "$@"

