#!/usr/bin/env bash # Generate hardware.nix for a registered host. # # Run this on the NEW machine (the one whose hardware you want captured), # inside this repo. Two contexts are auto-detected: set -euo pipefail NAME="" REPO_ROOT="." while (($#)); do case "$1" in --repo-root) REPO_ROOT="${2:?missing path}"; shift 2 ;; -h|--help) awk '/^#!/ {next} /^[^#]/ {exit} {sub(/^# ?/, ""); print}' "$0" exit 0 ;; -*) echo "[-] unknown flag: $1" >&2; exit 1 ;; *) if [[ -z "$NAME" ]]; then NAME="$1"; shift else echo "[-] unexpected positional arg: $1" >&2; exit 1 fi ;; esac done if [[ -z "$NAME" ]]; then echo "[-] usage: $0 " >&2 exit 1 fi cd "$REPO_ROOT" target="hosts/${NAME}/hardware.nix" if [[ ! -d "hosts/${NAME}" ]]; then echo "[-] hosts/${NAME} does not exist." >&2 echo " Run \`just register-host ${NAME}\` first." >&2 exit 1 fi if ! command -v nixos-generate-config >/dev/null 2>&1; then echo "[-] nixos-generate-config not found." >&2 echo " Run this on a NixOS machine (running system or installer ISO)." >&2 exit 2 fi # Detect installer-mounted-at-/mnt vs running-system. extra_args=() if mountpoint -q /mnt 2>/dev/null && [[ -d /mnt/etc ]]; then echo "[+] Detected mounted target at /mnt — using --root /mnt" extra_args+=(--root /mnt) elif mountpoint -q /mnt 2>/dev/null; then echo "[!] /mnt is mounted but doesn't look like a NixOS target (no /mnt/etc)." echo " Continuing as if on a running system. Edit hardware.nix afterwards" echo " if disks aren't permanent." fi # Confirm before overwriting a non-placeholder hardware.nix. if [[ -f "$target" ]] && ! grep -q 'PLACEHOLDER hardware.nix' "$target"; then echo "[!] $target already exists and doesn't look like a placeholder." >&2 if [[ -t 0 ]]; then read -r -p "Overwrite? (yes/[no]) " confirm [[ "$confirm" == "yes" ]] || { echo "aborted."; exit 1; } else echo "[-] non-interactive; refusing to overwrite. Delete $target first." >&2 exit 1 fi fi echo "[+] Generating hardware config..." # The redirect runs in the user's shell BEFORE sudo, so the file is owned # by the invoking user. sudo is needed because nixos-generate-config # probes /proc, /sys, and may need to read mounted filesystems. sudo nixos-generate-config --show-hardware-config "${extra_args[@]}" > "$target" echo "[+] Wrote $target" if command -v git >/dev/null && git rev-parse >/dev/null 2>&1; then echo "[+] git diff:" git --no-pager diff -- "$target" || true fi