#!/usr/bin/env bash set -euo pipefail # Resolve paths relative to this script, not the caller's CWD cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" HOST="$1" FLAKE=".#${HOST}" KEY_DIR="./host-keys/${HOST}" USER="${2:-root}" # Validate if [ ! -d "$KEY_DIR" ]; then echo "❌ No host key directory found for '${HOST}'" exit 1 fi # Validate the per-host secrets file exists SECRETS_FILE="secrets/${HOST}.yaml" if [ ! -f "$SECRETS_FILE" ]; then echo "❌ No secrets file found at ${SECRETS_FILE}" echo " Run: sops ${SECRETS_FILE}" exit 1 fi # ---- Compare host key fingerprints and replace if different ---- LOCAL_FINGERPRINT=$(ssh-keygen -lf "${KEY_DIR}/ssh_host_ed25519_key.pub" 2>/dev/null | awk '{print $2}') REMOTE_FINGERPRINT=$(ssh "${USER}@${HOST}" ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub 2>/dev/null | awk '{print $2}') if [ "$LOCAL_FINGERPRINT" != "$REMOTE_FINGERPRINT" ]; then echo "→ [${HOST}] Host key mismatch! Replacing..." echo " Local: ${LOCAL_FINGERPRINT}" echo " Remote: ${REMOTE_FINGERPRINT}" # Copy the pre-generated key to replace the VM's auto-generated one scp "${KEY_DIR}/ssh_host_ed25519_key" "${USER}@${HOST}:/etc/ssh/ssh_host_ed25519_key" scp "${KEY_DIR}/ssh_host_ed25519_key.pub" "${USER}@${HOST}:/etc/ssh/ssh_host_ed25519_key.pub" ssh "${USER}@${HOST}" chmod 600 /etc/ssh/ssh_host_ed25519_key ssh "${USER}@${HOST}" chmod 644 /etc/ssh/ssh_host_ed25519_key.pub echo "→ [${HOST}] Key replaced. You may get a WARNING on next SSH (host key changed)." echo " Remove old key with: ssh-keygen -R ${HOST}" else echo "→ [${HOST}] Host keys match, no action needed" fi # Deploy echo "→ [${HOST}] Deploying with nixos-rebuild..." nixos-rebuild switch \ --flake "$FLAKE" \ --target-host "${USER}@${HOST}" \ --sudo