main
1#!/usr/bin/env bash
2
3# Kyushu (Fedora CSB) Bootstrap Script
4# Description: Installs Nix (Determinate) and deploys system-manager config
5#
6# Prerequisites: Fedora CSB installed, user has sudo access
7# Usage: ./bootstrap.sh
8# Or remotely: ssh vdemeest@kyushu.home 'bash -s' < imperative/kyushu/bootstrap.sh
9#
10# Can also be sourced to run individual phases without poisoning the calling
11# shell with errexit:
12# bash -c 'source imperative/kyushu/bootstrap.sh && setup_tpm'
13
14# Only enable strict mode when executed directly, not when sourced — otherwise
15# a failing command would kill the interactive shell that sourced this file.
16if [[ "${BASH_SOURCE[0]:-}" == "${0}" ]]; then
17 set -euo pipefail
18fi
19
20readonly GREEN='\033[0;32m'
21readonly YELLOW='\033[1;33m'
22readonly RED='\033[0;31m'
23readonly NC='\033[0m'
24
25REPO_URL="${REPO_URL:-https://git.sbr.pm/home.git}"
26REPO_PATH="${REPO_PATH:-$HOME/src/home}"
27SYSTEM_CONFIG="${SYSTEM_CONFIG:-kyushu}"
28
29log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
30log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
31log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
32
33check_root() {
34 if [[ $EUID -eq 0 ]]; then
35 log_error "Run as your regular user, not root (sudo is used when needed)"
36 exit 1
37 fi
38}
39
40# --- Phase 1: Nix ---
41
42install_nix() {
43 if command -v nix &>/dev/null; then
44 log_info "Nix already installed: $(nix --version)"
45 return 0
46 fi
47
48 log_info "Installing Nix (Determinate Systems installer)..."
49 curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install
50
51 # Source nix for this session
52 if [[ -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]]; then
53 # shellcheck disable=SC1091
54 . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
55 fi
56
57 log_info "Nix installed: $(nix --version)"
58}
59
60configure_nix() {
61 local nix_conf="${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf"
62 mkdir -p "$(dirname "$nix_conf")"
63
64 # Determinate installer enables flakes by default, but ensure our preferences
65 if [[ ! -f "$nix_conf" ]] || ! grep -q 'use-xdg-base-directories' "$nix_conf" 2>/dev/null; then
66 cat >"$nix_conf" <<-'EOF'
67 experimental-features = nix-command flakes
68 use-xdg-base-directories = true
69 EOF
70 log_info "Nix config written to $nix_conf"
71 else
72 log_info "Nix config already exists"
73 fi
74}
75
76# --- Phase 2: Repository ---
77
78clone_repo() {
79 if [[ -d "$REPO_PATH/.git" ]]; then
80 log_info "Repository exists at $REPO_PATH, pulling..."
81 git -C "$REPO_PATH" pull --ff-only || log_warn "Pull failed, continuing with existing"
82 return 0
83 fi
84
85 log_info "Cloning $REPO_URL → $REPO_PATH"
86 mkdir -p "$(dirname "$REPO_PATH")"
87 git clone "$REPO_URL" "$REPO_PATH"
88}
89
90# --- Phase 3: SELinux policy for Nix + systemd ---
91
92setup_selinux_policy() {
93 if ! command -v getenforce &>/dev/null || [[ "$(getenforce)" == "Disabled" ]]; then
94 log_info "SELinux not enforcing, skipping policy"
95 return 0
96 fi
97
98 if sudo semodule -l 2>/dev/null | grep -q nix-systemd; then
99 log_info "SELinux nix-systemd policy already installed"
100 return 0
101 fi
102
103 log_info "Installing SELinux policy for Nix + systemd integration..."
104
105 # Ensure build tools are available
106 sudo dnf install -y checkpolicy policycoreutils-python-utils
107
108 local tmpdir
109 tmpdir=$(mktemp -d)
110
111 cat >"${tmpdir}/nix-systemd.te" <<'POLICY'
112module nix-systemd 1.0;
113
114require {
115 type init_t;
116 type default_t;
117 class file { read open getattr execute execute_no_trans map };
118 class dir { search getattr open read };
119 class lnk_file { read getattr };
120}
121
122# Allow systemd (init_t) to read unit files with default_t context
123# This occurs when system-manager symlinks units into /etc/systemd/system/
124# pointing to /nix/store paths which have default_t SELinux context
125allow init_t default_t:dir { search getattr open read };
126allow init_t default_t:file { read open getattr execute execute_no_trans map };
127allow init_t default_t:lnk_file { read getattr };
128POLICY
129
130 checkmodule -M -m -o "${tmpdir}/nix-systemd.mod" "${tmpdir}/nix-systemd.te"
131 semodule_package -o "${tmpdir}/nix-systemd.pp" -m "${tmpdir}/nix-systemd.mod"
132 sudo semodule -i "${tmpdir}/nix-systemd.pp"
133
134 rm -rf "${tmpdir}"
135 log_info "SELinux policy installed"
136}
137
138# --- Phase 4: System config files ---
139# Generated by nix from globals.nix, deployed without system-manager.
140# system-manager's activation clobbers /etc/profile.d, /etc/systemd/system,
141# and /etc/tmpfiles.d with nix-store symlinks, breaking Fedora's shell/NSS.
142
143setup_system_configs() {
144 log_info "Building and deploying system config files..."
145
146 # Ensure nix is in PATH
147 if ! command -v nix &>/dev/null; then
148 # shellcheck disable=SC1091
149 . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
150 fi
151
152 cd "$REPO_PATH"
153
154 local config_path
155 config_path=$(nix build ".#fedoraConfigs.${SYSTEM_CONFIG}" --no-link --print-out-paths)
156
157 log_info "Built: $config_path"
158 log_info "Deploying config files..."
159 sudo "${config_path}/deploy"
160
161 log_info "System config files deployed!"
162}
163
164# --- Phase 5: Native apps (dnf/flatpak) ---
165
166install_native_apps() {
167 log_info "Installing native apps..."
168
169 # GPU Screen Recorder is not in Fedora's official repositories.
170 log_info "Enabling GPU Screen Recorder COPR..."
171 sudo dnf copr enable -y brycensranch/gpu-screen-recorder-git
172
173 # Niri compositor + Wayland essentials + native multimedia apps
174 log_info "Installing niri, Wayland support, and native multimedia apps..."
175 sudo dnf install -y \
176 acpi \
177 brightnessctl \
178 powertop \
179 podman podman-docker \
180 niri \
181 wl-mirror \
182 kitty \
183 mpv \
184 gpu-screen-recorder \
185 gtk4-layer-shell \
186 xwayland-satellite \
187 xdg-desktop-portal-gnome \
188 xdg-desktop-portal-gtk \
189 libvirt
190
191 # Flatpak apps (sandboxed, auto-updating)
192 if ! command -v flatpak &>/dev/null; then
193 log_info "Installing flatpak..."
194 sudo dnf install -y flatpak
195 flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
196 fi
197
198 local flatpaks=(
199 com.slack.Slack
200 us.zoom.Zoom
201 )
202 for app in "${flatpaks[@]}"; do
203 if ! flatpak info "$app" &>/dev/null 2>&1; then
204 log_info "Installing $app..."
205 flatpak install -y flathub "$app"
206 else
207 log_info "$app already installed"
208 fi
209 done
210
211 # 1Password (dedicated RPM repo)
212 if ! rpm -q 1password &>/dev/null; then
213 log_info "Installing 1Password..."
214 sudo rpm --import https://downloads.1password.com/linux/keys/1password.asc
215 sudo tee /etc/yum.repos.d/1password.repo <<-'EOF'
216 [1password]
217 name=1Password Stable Channel
218 baseurl=https://downloads.1password.com/linux/rpm/stable/$basearch
219 enabled=1
220 gpgcheck=1
221 repo_gpgcheck=1
222 gpgkey=https://downloads.1password.com/linux/keys/1password.asc
223 EOF
224 sudo dnf install -y 1password 1password-cli
225 fi
226}
227
228# --- Phase 6: TPM 2.0 access ---
229
230setup_tpm() {
231 log_info "Configuring TPM 2.0 access..."
232
233 if [[ ! -e /dev/tpmrm0 && ! -e /dev/tpm0 ]]; then
234 log_warn "No TPM device found (/dev/tpm0, /dev/tpmrm0); skipping"
235 return 0
236 fi
237
238 # tpm2-tools gives tpm2_* utilities for inspection/testing
239 if ! command -v tpm2_pcrread &>/dev/null; then
240 sudo dnf install -y tpm2-tools
241 fi
242
243 # The tss group owns the TPM resource-manager device; membership is
244 # required for userspace access (age-plugin-tpm, ssh-tpm-agent, etc.)
245 if id -nG "$USER" | grep -qw tss; then
246 log_info "$USER already in tss group"
247 else
248 log_info "Adding $USER to tss group..."
249 sudo usermod -aG tss "$USER"
250 log_warn "Log out/in (or reboot) for tss group membership to take effect"
251 fi
252}
253
254# --- Phase 7: LUKS FIDO2 (YubiKey) ---
255
256setup_luks_fido2() {
257 local luks_dev
258 luks_dev=$(blkid -t TYPE=crypto_LUKS -o device 2>/dev/null | head -1)
259
260 if [[ -z "$luks_dev" ]]; then
261 log_warn "No LUKS device found; skipping FIDO2 enrollment"
262 return 0
263 fi
264
265 log_info "Found LUKS device: $luks_dev"
266
267 # Check if FIDO2 is already enrolled
268 if sudo systemd-cryptenroll "$luks_dev" --fido2-device=list 2>/dev/null | grep -q 'fido2'; then
269 log_info "FIDO2 already available"
270 else
271 log_warn "No FIDO2 device detected. Plug in YubiKey, then run:"
272 log_warn " sudo systemd-cryptenroll $luks_dev --fido2-device=auto --fido2-with-client-pin=no"
273 fi
274
275 # Ensure dracut includes fido2 support in initramfs
276 if ! lsinitrd 2>/dev/null | grep -q fido2; then
277 log_info "Adding fido2 support to initramfs..."
278 sudo dracut --add fido2 -f
279 log_info "Initramfs rebuilt with fido2 support"
280 else
281 log_info "Initramfs already has fido2 support"
282 fi
283}
284
285# --- Phase 7b: YubiKey sudo (pam-u2f) ---
286
287setup_yubikey_sudo() {
288 if ! rpm -q pam-u2f &>/dev/null; then
289 log_info "Installing pam-u2f..."
290 sudo dnf install -y pam-u2f pamu2fcfg
291 else
292 log_info "pam-u2f already installed"
293 fi
294
295 local u2f_keys="${HOME}/.config/Yubico/u2f_keys"
296 if [[ ! -f "$u2f_keys" ]]; then
297 log_info "Registering YubiKey for PAM U2F — touch the key when it blinks..."
298 mkdir -p "$(dirname "$u2f_keys")"
299 pamu2fcfg >"$u2f_keys"
300 log_info "YubiKey registered at $u2f_keys"
301 log_warn "To add a backup key later: pamu2fcfg -n >> $u2f_keys"
302 else
303 log_info "YubiKey already registered at $u2f_keys"
304 fi
305
306 # Configure sudo to accept YubiKey touch (sufficient = no password needed)
307 local sudo_pam="/etc/pam.d/sudo"
308 if ! grep -q pam_u2f.so "$sudo_pam" 2>/dev/null; then
309 log_info "Adding pam_u2f to $sudo_pam (sufficient — falls back to password)..."
310 sudo sed -i '1a auth sufficient pam_u2f.so' "$sudo_pam"
311 log_info "YubiKey sudo configured"
312 else
313 log_info "pam_u2f already in $sudo_pam"
314 fi
315}
316
317# --- Phase 8: unscd for nix NSS resolution ---
318
319setup_unscd() {
320 # Nix glibc can't load system NSS modules (libnss_sss.so) so nix programs
321 # can't resolve LDAP/SSSD users. unscd creates /var/run/nscd/socket which
322 # nix glibc queries automatically. Must be built with system gcc/glibc
323 # so it can load system NSS modules.
324 if systemctl is-active --quiet unscd 2>/dev/null; then
325 log_info "unscd already running"
326 return 0
327 fi
328
329 log_info "Building and installing unscd for nix NSS resolution..."
330 sudo dnf install -y gcc make
331
332 local tmpdir
333 tmpdir=$(mktemp -d)
334 curl -sSL https://busybox.net/~vda/unscd/nscd-0.54.c -o "${tmpdir}/nscd.c"
335 # Newer glibc removed __nss_disable_nscd from headers; provide a stub
336 sed -i '/^void __nss_disable_nscd(/c\void __nss_disable_nscd(void (*hell)(size_t, struct traced_file*)) {}' "${tmpdir}/nscd.c"
337 PATH=/usr/bin:/usr/sbin /usr/bin/gcc -O2 -o "${tmpdir}/unscd" "${tmpdir}/nscd.c"
338 sudo install -m 755 "${tmpdir}/unscd" /usr/local/sbin/unscd
339 rm -rf "${tmpdir}"
340
341 # Create systemd service
342 sudo tee /etc/systemd/system/unscd.service >/dev/null <<-'EOF'
343 [Unit]
344 Description=Name Service Cache Daemon (unscd for nix)
345 After=sssd.service network.target
346
347 [Service]
348 Type=forking
349 ExecStart=/usr/local/sbin/unscd
350 Restart=on-failure
351
352 [Install]
353 WantedBy=multi-user.target
354 EOF
355
356 sudo systemctl daemon-reload
357 sudo systemctl enable --now unscd
358 log_info "unscd installed and running"
359}
360
361# --- Phase 8: WireGuard ---
362
363setup_power() {
364 log_info "Configuring power management..."
365
366 # Powertop auto-tune service
367 if [[ ! -f /etc/systemd/system/powertop.service ]]; then
368 log_info "Creating powertop auto-tune service..."
369 sudo tee /etc/systemd/system/powertop.service >/dev/null <<-'EOF'
370 [Unit]
371 Description=PowerTOP auto-tune
372 After=multi-user.target
373
374 [Service]
375 Type=oneshot
376 ExecStart=/usr/sbin/powertop --auto-tune
377
378 [Install]
379 WantedBy=multi-user.target
380 EOF
381 sudo systemctl daemon-reload
382 sudo systemctl enable --now powertop.service
383 else
384 log_info "powertop service already exists"
385 fi
386
387 # Configure tuned-ppd mapping (PPD profiles → tuned profiles)
388 # All values must be unique per map (injective) for reversibility.
389 # AC: power-saver→powersave, balanced→balanced, performance→latency-performance
390 # Battery: power-saver→powersave, balanced→balanced-battery, performance→balanced
391 if command -v tuned-adm &>/dev/null; then
392 log_info "Configuring tuned-ppd..."
393 sudo tee /etc/tuned/ppd.conf >/dev/null <<-'EOF'
394 [main]
395 default=balanced
396 battery_detection=true
397 sysfs_acpi_monitor=true
398
399 [profiles]
400 power-saver=powersave
401 balanced=balanced
402 performance=latency-performance
403
404 [battery]
405 balanced=balanced-battery
406 performance=balanced
407 EOF
408 sudo systemctl restart tuned tuned-ppd
409 log_info "tuned-ppd configured"
410 fi
411}
412
413setup_wireguard() {
414 # Use Fedora-native wg-quick service (proper SELinux context)
415 # Config file is managed by system-manager in /etc/wireguard/wg0.conf
416 log_info "Setting up WireGuard (native service)..."
417 sudo dnf install -y wireguard-tools
418 sudo systemctl enable wg-quick@wg0
419
420 # Trust wg0 interface in firewall (allows SSH and all traffic over VPN)
421 if command -v firewall-cmd &>/dev/null; then
422 log_info "Adding wg0 to firewalld trusted zone..."
423 sudo firewall-cmd --zone=trusted --add-interface=wg0 --permanent
424 sudo firewall-cmd --reload
425 fi
426
427 if [[ -f /etc/wireguard/private.key ]]; then
428 log_info "WireGuard private key exists, starting service..."
429 sudo systemctl start wg-quick@wg0
430 return 0
431 fi
432
433 log_warn "WireGuard private key not found at /etc/wireguard/private.key"
434 log_warn ""
435 log_warn "To set up WireGuard, either:"
436 log_warn " 1. Copy existing key: sudo cp /path/to/backup/private.key /etc/wireguard/"
437 log_warn " 2. Generate new key: wg genkey | sudo tee /etc/wireguard/private.key"
438 log_warn " Then update globals.nix with new pubkey: sudo cat /etc/wireguard/private.key | wg pubkey"
439 log_warn " (current VPN IP: 10.100.0.19)"
440 log_warn ""
441 log_warn "After placing the key: sudo chmod 600 /etc/wireguard/private.key"
442 log_warn "Then re-run: sudo systemctl restart wg-quick@wg0"
443}
444
445# --- Phase 9: Home-manager ---
446
447setup_home_manager() {
448 log_info "Setting up home-manager..."
449
450 # Ensure nix is in PATH
451 if ! command -v nix &>/dev/null; then
452 # shellcheck disable=SC1091
453 . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
454 fi
455
456 cd "$REPO_PATH"
457
458 # Build and activate home-manager
459 nix run home-manager -- switch --flake ".#vdemeest@${SYSTEM_CONFIG}"
460
461 log_info "Home-manager activated!"
462}
463
464# --- Phase 10: Shell setup ---
465
466setup_shell() {
467 local zsh_path="$HOME/.local/state/nix/profile/bin/zsh"
468
469 if ! grep -q "$zsh_path" /etc/shells 2>/dev/null; then
470 log_info "Adding nix zsh to /etc/shells..."
471 echo "$zsh_path" | sudo tee -a /etc/shells
472 fi
473
474 # CSB uses LDAP/FreeIPA, chsh won't work — use bashrc exec instead
475 if ! grep -q 'exec.*zsh' ~/.bashrc 2>/dev/null; then
476 log_info "Configuring bash to exec into zsh..."
477 # shellcheck disable=SC2016
478 echo '[[ $- == *i* && -x "$HOME/.local/state/nix/profile/bin/zsh" ]] && exec "$HOME/.local/state/nix/profile/bin/zsh"' >>~/.bashrc
479 fi
480
481 log_info "Shell configured (zsh via bashrc exec)"
482}
483
484# --- Summary ---
485
486print_summary() {
487 log_info ""
488 log_info "╔═══════════════════════════════════════════╗"
489 log_info "║ Kyushu (Fedora CSB) Bootstrap Done ║"
490 log_info "╠═══════════════════════════════════════════╣"
491 log_info "║ Nix: ✓ installed ║"
492 log_info "║ System configs: ✓ written ║"
493 log_info "║ Home-manager: ✓ activated ║"
494 log_info "║ Native apps: ✓ installed ║"
495 log_info "╠═══════════════════════════════════════════╣"
496 log_info "║ Rebuild home: ║"
497 log_info "║ Rebuild home: ║"
498 log_info "║ home-manager switch --flake .#vdemeest@kyushu ║"
499 log_info "╚═══════════════════════════════════════════╝"
500}
501
502# --- Main ---
503
504main() {
505 log_info "Bootstrapping kyushu (Fedora CSB)..."
506 log_info " Repo: $REPO_URL → $REPO_PATH"
507 log_info " Config: $SYSTEM_CONFIG"
508 echo
509
510 check_root
511 install_nix
512 configure_nix
513 clone_repo
514 setup_selinux_policy
515 install_native_apps
516 setup_tpm
517 setup_luks_fido2
518 setup_unscd
519 setup_system_configs
520 setup_power
521 setup_wireguard
522 setup_yubikey_sudo
523 setup_shell
524 setup_home_manager
525 print_summary
526}
527
528# Only run main when executed directly, not when sourced. This lets you run
529# individual phases, e.g. (use bash, the script targets bash):
530# source imperative/kyushu/bootstrap.sh
531# setup_tpm
532if [[ "${BASH_SOURCE[0]:-}" == "${0}" ]]; then
533 main "$@"
534fi