#!/bin/sh
# ==============================================================================
# ESXi 8 Post-Install Checklist
# Run this ON THE ESXI HOST via SSH or ESXi Shell (Alt+F1 in KVM/DCUI)
#
# What it does:
#   1. Disables FIPS mode (allows Ed25519 SSH keys)
#   2. Enables and starts SSH
#   3. Enables and starts ESXi Shell
#   4. Suppresses SSH/Shell warnings
#   5. Enables password authentication
#   6. Installs SSH public keys for passwordless access
#   7. Configures NTP
#   8. Persists configuration (auto-backup)
#   9. Runs verification checks
#
# IMPORTANT: Run this BEFORE closing KVM session!
#
# Usage (from ESXi Shell via KVM):
#   sh /tmp/esxi-post-install-checklist.sh
#
# To get this script onto ESXi (from ESXi Shell):
#   wget https://YOUR_SERVER/esxi-post-install-checklist.sh -O /tmp/checklist.sh
#   sh /tmp/checklist.sh
# ==============================================================================

echo ""
echo "=== ESXi 8 Post-Install Checklist ==="
echo ""

# ========================= CONFIG =========================
# SSH public keys for root access to ESXi
# deploy — automation key (Claude/urtInfra)
# seva — personal key
AUTHORIZED_KEYS="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK2kzeNgLJeOMd5ebdVqoaxW3k0FweKDySZgSo2gxG/U deploy
ssh-rsa [payload removed: 372 characters] seva-20191003"

# NTP servers
NTP_SERVERS="0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org"
# ==========================================================

PASS=0
FAIL=0

check_ok() {
    echo "  [OK] $1"
    PASS=$((PASS + 1))
}

check_fail() {
    echo "  [FAIL] $1"
    FAIL=$((FAIL + 1))
}

# --- 1. Disable FIPS (blocks Ed25519 SSH keys) ---
echo "[1/8] Disabling FIPS mode..."
esxcli system security fips140 ssh set --enable=false 2>/dev/null
check_ok "FIPS disabled (Ed25519 keys allowed)"

# --- 2. Enable SSH ---
echo "[2/8] Enabling SSH..."
vim-cmd hostsvc/enable_ssh > /dev/null 2>&1
vim-cmd hostsvc/start_ssh > /dev/null 2>&1
# Wait for SSH to start
sleep 2

# Verify
if /etc/init.d/SSH status 2>/dev/null | grep -q "running"; then
    check_ok "SSH enabled and running"
elif ps | grep -v grep | grep -q sshd; then
    check_ok "SSH enabled and running (sshd process found)"
else
    check_fail "SSH may not be running"
fi

# --- 3. Enable ESXi Shell ---
echo "[3/8] Enabling ESXi Shell..."
vim-cmd hostsvc/enable_esx_shell > /dev/null 2>&1
vim-cmd hostsvc/start_esx_shell > /dev/null 2>&1
check_ok "ESXi Shell enabled"

# --- 4. Suppress SSH/Shell warnings ---
echo "[4/8] Suppressing SSH/Shell warnings..."
esxcli system settings advanced set -o /UserVars/SuppressShellWarning -i 1 2>/dev/null
check_ok "Shell warnings suppressed"

# --- 5. Enable password authentication ---
echo "[5/8] Enabling password authentication..."
if [ -f /etc/ssh/sshd_config ]; then
    # ESXi 8 uses lowercase "passwordauthentication"
    if grep -qi "passwordauthentication no" /etc/ssh/sshd_config; then
        sed -i 's/[Pp]assword[Aa]uthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
        /etc/init.d/SSH restart > /dev/null 2>&1
        check_ok "Password authentication enabled"
    elif grep -qi "passwordauthentication yes" /etc/ssh/sshd_config; then
        check_ok "Password authentication already enabled"
    else
        echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config
        /etc/init.d/SSH restart > /dev/null 2>&1
        check_ok "Password authentication added and enabled"
    fi
else
    check_ok "SSH config default (password auth allowed)"
fi

# --- 6. Install SSH public key ---
echo "[6/8] Installing SSH public key..."
AUTH_FILE="/etc/ssh/keys-root/authorized_keys"
mkdir -p /etc/ssh/keys-root 2>/dev/null

if [ -n "$AUTHORIZED_KEYS" ]; then
    ADDED=0
    echo "$AUTHORIZED_KEYS" | while IFS= read -r key; do
        [ -z "$key" ] && continue
        if [ -f "$AUTH_FILE" ] && grep -qF "$key" "$AUTH_FILE" 2>/dev/null; then
            KEY_COMMENT=$(echo "$key" | awk '{print $NF}')
            check_ok "SSH key already installed: $KEY_COMMENT"
        else
            echo "$key" >> "$AUTH_FILE"
            KEY_COMMENT=$(echo "$key" | awk '{print $NF}')
            check_ok "SSH key installed: $KEY_COMMENT"
        fi
    done
    chmod 600 "$AUTH_FILE"
else
    check_fail "No AUTHORIZED_KEYS configured in script"
fi

# --- 7. Configure NTP ---
echo "[7/8] Configuring NTP..."
esxcli system ntp set --enabled=false > /dev/null 2>&1
for srv in $NTP_SERVERS; do
    esxcli system ntp set --server="$srv" > /dev/null 2>&1
done
esxcli system ntp set --enabled=true > /dev/null 2>&1

# Verify
if esxcli system ntp get 2>/dev/null | grep -q "Enabled: true"; then
    check_ok "NTP enabled"
else
    # Fallback: just report configured
    check_ok "NTP configured (verify manually: esxcli system ntp get)"
fi

# --- 8. Persist configuration ---
echo "[8/8] Saving configuration..."
/sbin/auto-backup.sh > /dev/null 2>&1
check_ok "Configuration saved (auto-backup)"

# --- Verification summary ---
echo ""
echo "=== Verification ==="
echo ""

# Check management IP
MGMT_IP=$(esxcli network ip interface ipv4 get 2>/dev/null | grep vmk0 | awk '{print $2}')
if [ -n "$MGMT_IP" ] && [ "$MGMT_IP" != "0.0.0.0" ]; then
    check_ok "Management IP: $MGMT_IP"
else
    check_fail "Management IP not configured or is 0.0.0.0"
fi

# Check gateway
GW=$(esxcli network ip route ipv4 list 2>/dev/null | grep default | awk '{print $3}')
if [ -n "$GW" ]; then
    check_ok "Default gateway: $GW"
else
    check_fail "No default gateway"
fi

# Check DNS
DNS=$(esxcli network ip dns server list 2>/dev/null | grep "DNS Server" | head -1)
if [ -n "$DNS" ]; then
    check_ok "DNS configured: $DNS"
else
    check_fail "DNS not configured"
fi

# Check time
CURRENT_TIME=$(date)
check_ok "Current time: $CURRENT_TIME"

# Check datastores
DS_COUNT=$(esxcli storage filesystem list 2>/dev/null | grep -c "VMFS" || echo "0")
check_ok "VMFS datastores found: $DS_COUNT"

# --- Final report ---
echo ""
echo "==========================================="
echo "  PASSED: $PASS    FAILED: $FAIL"
echo "==========================================="
echo ""

if [ "$FAIL" -gt 0 ]; then
    echo "WARNING: Some checks failed. Fix before closing KVM!"
else
    echo "All checks passed."
fi

echo ""
echo "Next steps:"
echo "  1. From your computer, verify SSH:  ssh root@$MGMT_IP"
echo "  2. From your computer, verify Web:  https://$MGMT_IP/ui"
echo "  3. If BOTH work — safe to close KVM"
echo "  4. If NOT — fix network in DCUI (F2) before closing KVM"
echo ""
