#!/bin/bash
# vmsetup.sh — Rocky/RHEL branch
# Vision Encompassed LLC
#
# Run once, interactively, on a freshly cloned Rocky VM while its VIF is
# still isolated on PLACEHOLDER-VLAN4094, BEFORE moving the VIF to a real
# VLAN. Sets hostname, static IP, machine-id, SSH host keys, verifies wheel
# membership, dispatches CA-trust hook if present, and re-inits AIDE last.
#
# Password/Vault-push logic is intentionally a stub — Vault is not live yet.
# Do not fill this in until vault-01 is live and an AppRole exists for it.

set -euo pipefail

echo "=== vmsetup.sh (Rocky) ==="

# --- 1. Gather required values ---
read -rp "Hostname (e.g. vault-01): " VM_HOSTNAME
read -rp "Static IP with CIDR (e.g. 10.0.35.9/24): " VM_IP
read -rp "Gateway (e.g. 10.0.35.1): " VM_GW
read -rp "DNS server (e.g. 10.0.30.21) [10.0.30.21]: " VM_DNS
VM_DNS=${VM_DNS:-10.0.30.21}
read -rp "NetworkManager connection/device name (check: nmcli connection show) [enX1]: " VM_CONN
VM_CONN=${VM_CONN:-enX1}

echo
echo "About to configure:"
echo "  Hostname: $VM_HOSTNAME"
echo "  IP:       $VM_IP"
echo "  Gateway:  $VM_GW"
echo "  DNS:      $VM_DNS"
echo "  Conn:     $VM_CONN"
read -rp "Confirm? (y/N): " CONFIRM
[[ "$CONFIRM" =~ ^[Yy]$ ]] || { echo "Aborted."; exit 1; }

# --- 2. Verify wheel membership BEFORE relying on sudo for anything else ---
echo "--- Checking wheel membership ---"
if ! id -nG "$USER" | grep -qw wheel; then
    echo "WARNING: $USER is NOT in the wheel group."
    echo "This is the known Rocky Anaconda 'Make administrator' checkbox bug."
    echo "Fix manually: su - (using install-time root password), then:"
    echo "  usermod -aG wheel $USER"
    echo "Re-login and re-run this script after fixing."
    exit 1
else
    echo "OK: $USER is in wheel."
fi

# --- 3. Hostname ---
echo "--- Setting hostname ---"
sudo hostnamectl set-hostname "$VM_HOSTNAME"

# --- 4. Static IP via nmcli (explicit manual method, verified not left on auto) ---
echo "--- Setting static IP via nmcli ---"
sudo nmcli connection modify "$VM_CONN" ipv4.addresses "$VM_IP"
sudo nmcli connection modify "$VM_CONN" ipv4.gateway "$VM_GW"
sudo nmcli connection modify "$VM_CONN" ipv4.dns "$VM_DNS"
sudo nmcli connection modify "$VM_CONN" ipv4.method manual
sudo nmcli connection modify "$VM_CONN" connection.autoconnect yes
sudo nmcli connection down "$VM_CONN" || true
sudo nmcli connection up "$VM_CONN"

ACTUAL_METHOD=$(nmcli -g ipv4.method connection show "$VM_CONN")
if [[ "$ACTUAL_METHOD" != "manual" ]]; then
    echo "ERROR: ipv4.method shows '$ACTUAL_METHOD', expected 'manual'. Aborting before further changes."
    exit 1
fi
echo "OK: ipv4.method confirmed manual."

# --- 5. Machine-ID regen (Rocky/XCP-ng bug: systemd-machine-id-setup pulls VM UUID) ---
echo "--- Regenerating machine-id ---"
sudo rm -f /etc/machine-id
cat /proc/sys/kernel/random/uuid | tr -d '-' | sudo tee /etc/machine-id > /dev/null
sudo chmod 444 /etc/machine-id
if [[ -d /var/lib/dbus ]]; then
    sudo ln -sf /etc/machine-id /var/lib/dbus/machine-id
fi
echo "New machine-id: $(sudo cat /etc/machine-id)"

# --- 6. SSH host key regen ---
echo "--- Regenerating SSH host keys ---"
sudo rm -f /etc/ssh/ssh_host_*
sudo ssh-keygen -A
sudo systemctl restart sshd

# --- 7. Bootstrap CA trust against cert-authority-01 ---
CA_FINGERPRINT="543a19671c57b47888e17ebb22a73833d2826ee3cb82875eb883770c684d368e"
if command -v step >/dev/null 2>&1; then
    echo "--- Bootstrapping trust against cert-authority-01 ---"
    step ca bootstrap --ca-url https://10.0.30.6:443 --fingerprint "$CA_FINGERPRINT" --force \
        || echo "step ca bootstrap failed, continuing (flagging, not blocking)."
else
    echo "NOTE: step CLI not present on this template — CA bootstrap skipped. Install step CLI manually to enable trust."
fi

# --- 8. Password / Vault-push: generate per-VM password, store in Vault via AppRole ---
VMSETUP_ROLE_ID="7539c352-87eb-6196-4a43-174d3f586750"
VAULT_ADDR="https://10.0.35.9:8200"
VAULT_CACERT="/home/bryan/.step/certs/root_ca.crt"

if command -v vault >/dev/null 2>&1 && [[ -f "$VAULT_CACERT" ]]; then
    echo "--- Vault password push ---"
    read -rsp "Paste vmsetup AppRole secret_id (generate fresh via: vault write -f auth/approle/role/vmsetup/secret-id): " VMSETUP_SECRET_ID
    echo
    NEW_PASS=$(openssl rand -base64 24)
    VAULT_TOKEN=$(VAULT_ADDR="$VAULT_ADDR" VAULT_CACERT="$VAULT_CACERT" vault write -field=token auth/approle/login role_id="$VMSETUP_ROLE_ID" secret_id="$VMSETUP_SECRET_ID" 2>/dev/null)
    if [[ -n "$VAULT_TOKEN" ]]; then
        echo "$NEW_PASS" | sudo passwd --stdin bryan >/dev/null 2>&1 || echo "$NEW_PASS" | sudo chpasswd
        VAULT_ADDR="$VAULT_ADDR" VAULT_CACERT="$VAULT_CACERT" VAULT_TOKEN="$VAULT_TOKEN" \
            vault kv put "secret/vm-passwords/$(hostname)" bryan_password="$NEW_PASS" >/dev/null \
            && echo "Password rotated and pushed to Vault at secret/vm-passwords/$(hostname)." \
            || echo "WARNING: password rotated locally but Vault write failed — record manually."
    else
        echo "WARNING: AppRole login failed — password NOT rotated, continuing (flagging, not blocking)."
    fi
    unset VMSETUP_SECRET_ID NEW_PASS VAULT_TOKEN
else
    echo "NOTE: vault CLI or CA cert not present on this template — password push skipped."
fi

# --- 9. AIDE re-init — LITERAL LAST STEP, never assume current ---
echo "--- Re-initializing AIDE (last step) ---"
sudo aide --init
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
sudo aide --check

echo
echo "=== vmsetup.sh complete for $VM_HOSTNAME ==="
echo "Reboot now to verify hostname/IP/machine-id survive:"
echo "  sudo reboot"
echo "After reboot, verify with: hostnamectl status && ip a show $VM_CONN && cat /etc/machine-id"

echo ""
echo "===================================================="
echo "REMINDER — paste this on forge to update SSH config:"
echo "===================================================="
CLEAN_IP="${VM_IP%%/*}"
echo "sed -i '/^Host ${VM_HOSTNAME}\$/,/^\$/d' ~/.ssh/config && tee -a ~/.ssh/config <<'SSHEOF'"
echo "Host ${VM_HOSTNAME}"
echo "    ForwardAgent yes"
echo "    HostName ${CLEAN_IP}"
echo "    User bryan"
echo "    IdentityFile ~/.ssh/fleet-admin-ed25519-new"
echo ""
echo "SSHEOF"
echo "===================================================="
