feat: improve scripts and write tests
This commit is contained in:
32 files changed
+3817
-723
No files matched your search
+417
-260
@@ -1,83 +1,424 @@
|
||||
#!/usr/bin/env bash
|
||||
# Write a NixOS installer ISO to a USB stick (raw dd).
|
||||
#
|
||||
# The script self-elevates via sudo if not already running as root, so
|
||||
# you can run it as your normal user.
|
||||
# DESTRUCTIVE: everything on the target disk is erased. Safeguards:
|
||||
# * only whole disks are accepted (never partitions)
|
||||
# * a disk holding anything but auto-mount locations (/, /boot, /nix, /home,
|
||||
# swap, ...) is refused outright
|
||||
# * non-removable, non-USB disks need --allow-internal
|
||||
# * the ISO must not live on the disk being erased
|
||||
# * you must retype the device path to confirm (unless --yes)
|
||||
# * the written image is read back and compared with the ISO
|
||||
#
|
||||
# After booting the resulting USB on the target machine, fetch this repo
|
||||
# over the network with `git clone <url>` from the installer shell.
|
||||
# The script re-executes itself under sudo if it isn't root.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_PATH="$(readlink -f -- "${BASH_SOURCE[0]}")"
|
||||
SCRIPT_DIR="$(dirname -- "$SCRIPT_PATH")"
|
||||
# shellcheck source=lib/common.sh
|
||||
source "$SCRIPT_DIR/lib/common.sh"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: make-usb.sh [options]
|
||||
|
||||
if [[ -t 1 ]]; then
|
||||
GREEN=$'\e[32m'; YELLOW=$'\e[33m'; RED=$'\e[31m'; BLUE=$'\e[34m'
|
||||
BOLD=$'\e[1m'; RESET=$'\e[0m'
|
||||
else
|
||||
GREEN=""; YELLOW=""; RED=""; BLUE=""; BOLD=""; RESET=""
|
||||
fi
|
||||
log() { printf '%s[+]%s %s\n' "$GREEN" "$RESET" "$*"; }
|
||||
warn() { printf '%s[!]%s %s\n' "$YELLOW" "$RESET" "$*" >&2; }
|
||||
err() { printf '%s[-]%s %s\n' "$RED" "$RESET" "$*" >&2; }
|
||||
info() { printf '%s[i]%s %s\n' "$BLUE" "$RESET" "$*"; }
|
||||
die() { err "$1"; exit "${2:-1}"; }
|
||||
|
||||
--iso PATH ISO to write (prompted for if omitted)
|
||||
--device DEV target disk, e.g. /dev/sdb (chosen from a menu if omitted)
|
||||
--allow-internal allow disks that are neither removable nor on the USB bus
|
||||
--no-verify skip reading the written image back for comparison
|
||||
-y, --yes don't ask for confirmation (requires --iso and --device)
|
||||
-h, --help show this help
|
||||
|
||||
Exit codes: 0 ok, 1 aborted/other, 2 usage, 3 missing tools, 4 unsafe or
|
||||
invalid device/ISO, 5 checksum or write failure, 6 read-back verification failed.
|
||||
EOF
|
||||
}
|
||||
|
||||
ISO_PATH=""
|
||||
DEVICE=""
|
||||
ALLOW_INTERNAL=0
|
||||
ASSUME_YES=0
|
||||
VERIFY=1
|
||||
ORIG_ARGS=()
|
||||
ISO_BYTES=0
|
||||
DEV_BYTES=0
|
||||
|
||||
# Save original args before the parser shifts them away; needed if we
|
||||
# later re-exec under sudo.
|
||||
ORIG_ARGS=("$@")
|
||||
# /proc/swaps path; overridable so tests can fake it.
|
||||
PROC_SWAPS="${PROC_SWAPS:-/proc/swaps}"
|
||||
|
||||
while (($#)); do
|
||||
parse_args() {
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--iso=*) ISO_PATH="${1#*=}"; shift ;;
|
||||
--device=*|--dev=*) DEVICE="${1#*=}"; shift ;;
|
||||
--iso) need_value "$@"; ISO_PATH="$2"; shift 2 ;;
|
||||
--device|--dev) need_value "$@"; DEVICE="$2"; shift 2 ;;
|
||||
--allow-internal) ALLOW_INTERNAL=1; shift ;;
|
||||
--no-verify) VERIFY=0; shift ;;
|
||||
-y|--yes) ASSUME_YES=1; shift ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) die "unknown argument: $1 (see --help)" 2 ;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Block-device helpers. Everything below talks to lsblk/findmnt only through
|
||||
# fixed argument lists and never evals or word-splits device-reported text,
|
||||
# since model strings and labels are attacker-controlled (any USB device can
|
||||
# claim any model name).
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
is_block_device() { [[ -b "$1" ]]; }
|
||||
|
||||
# blk_field DEVICE COLUMN: one lsblk column for one device, reduced to
|
||||
# printable ASCII and trimmed. Empty if unknown.
|
||||
blk_field() {
|
||||
local v
|
||||
v="$(lsblk -dn -o "$2" "$1" 2>/dev/null || true)"
|
||||
v="${v%%$'\n'*}"
|
||||
v="$(printf '%s' "$v" | LC_ALL=C tr -cd '[:print:]')"
|
||||
v="${v#"${v%%[![:space:]]*}"}"
|
||||
printf '%s' "${v%"${v##*[![:space:]]}"}"
|
||||
}
|
||||
|
||||
# list_candidate_disks: whole disks only, one path per line.
|
||||
list_candidate_disks() {
|
||||
local name type
|
||||
lsblk -dnpr -o NAME,TYPE 2>/dev/null | while read -r name type; do
|
||||
[[ "$type" == disk ]] || continue
|
||||
case "$name" in
|
||||
/dev/sr*|/dev/loop*|/dev/ram*|/dev/zram*|/dev/dm-*|/dev/nbd*) continue ;;
|
||||
esac
|
||||
printf '%s\n' "$name"
|
||||
done
|
||||
}
|
||||
|
||||
# device_tree DEVICE: the device plus all partitions and holders (LUKS, LVM...).
|
||||
device_tree() { lsblk -lnp -o NAME "$1" 2>/dev/null || true; }
|
||||
|
||||
# mounts_of DEVICE: mount points backed by the disk or anything stacked on it.
|
||||
# Returns nonzero if the mount table can't be read; callers must treat that as
|
||||
# "unknown", never as "nothing mounted".
|
||||
mounts_of() {
|
||||
local tree table src tgt
|
||||
tree="$(device_tree "$1")"
|
||||
[[ -n "$tree" ]] || return 0
|
||||
table="$(findmnt -rn -o SOURCE,TARGET 2>/dev/null)" || return 1
|
||||
while read -r src tgt; do
|
||||
src="${src%%\[*}" # btrfs/bind: /dev/sda2[/@] -> /dev/sda2
|
||||
if grep -qxF -- "$src" <<<"$tree"; then
|
||||
printf '%b\n' "$tgt" # findmnt -r escapes spaces as \x20
|
||||
fi
|
||||
done <<<"$table"
|
||||
}
|
||||
|
||||
# has_swap DEVICE: true if swap is active on the disk or anything stacked on
|
||||
# it. Also true (fail closed) if we can't read the swap table at all.
|
||||
has_swap() {
|
||||
local tree s
|
||||
[[ -r "$PROC_SWAPS" ]] || return 0
|
||||
tree="$(device_tree "$1")"
|
||||
while read -r s _; do
|
||||
[[ -n "$s" && "$s" != Filename ]] || continue
|
||||
grep -qxF -- "$s" <<<"$tree" && return 0
|
||||
done < "$PROC_SWAPS"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Mount points we are willing to unmount automatically (desktop auto-mounts).
|
||||
is_automount_point() {
|
||||
case "$1" in
|
||||
--iso) ISO_PATH="${2:?missing path}"; shift 2 ;;
|
||||
--device|--dev) DEVICE="${2:?missing path}"; shift 2 ;;
|
||||
--allow-internal) ALLOW_INTERNAL=1; shift ;;
|
||||
--yes|-y) ASSUME_YES=1; shift ;;
|
||||
-h|--help)
|
||||
awk '/^#!/ {next} /^[^#]/ {exit} {sub(/^# ?/, ""); print}' "$0"
|
||||
exit 0 ;;
|
||||
*) die "unknown arg: $1" 2 ;;
|
||||
/run/media/*|/media/*|/mnt/*|/run/mnt/*) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
|
||||
# Self-elevate via sudo if not already root. We re-exec rather than tell
|
||||
# the user to prefix the command, so `just make-usb` and `./scripts/make-usb.sh`
|
||||
# both Just Work.
|
||||
if (( EUID != 0 )); then
|
||||
if ! command -v sudo >/dev/null 2>&1; then
|
||||
die "must run as root and sudo is not installed" 1
|
||||
# protected_mounts DEVICE: print every in-use mount (or [SWAP]) on this disk
|
||||
# that must NOT be unmounted behind the user's back. Allowlist, not blocklist:
|
||||
# any mount point we don't positively recognize as an auto-mount protects it.
|
||||
protected_mounts() {
|
||||
local mounts mp
|
||||
if ! mounts="$(mounts_of "$1")"; then
|
||||
printf '[mount table unreadable]\n'
|
||||
return 0
|
||||
fi
|
||||
# ORIG_ARGS may be empty; ${ORIG_ARGS[@]+"${ORIG_ARGS[@]}"} expands
|
||||
# safely under set -u even when the array is unset.
|
||||
exec sudo --preserve-env=PATH -- "$0" ${ORIG_ARGS[@]+"${ORIG_ARGS[@]}"}
|
||||
fi
|
||||
while IFS= read -r mp; do
|
||||
[[ -n "$mp" ]] || continue
|
||||
is_automount_point "$mp" || printf '%s\n' "$mp"
|
||||
done <<<"$mounts"
|
||||
if has_swap "$1"; then printf '[SWAP or swap table unreadable]\n'; fi
|
||||
}
|
||||
|
||||
# Require an interactive tty for any prompt we still need.
|
||||
need_tty=0
|
||||
[[ -z "$DEVICE" || -z "$ISO_PATH" ]] && need_tty=1
|
||||
(( ASSUME_YES )) || need_tty=1
|
||||
if (( need_tty )) && ! [[ -t 0 ]]; then
|
||||
die "stdin is not a tty; pass --iso, --device, and --yes for non-interactive use" 2
|
||||
fi
|
||||
is_external() {
|
||||
[[ "$(blk_field "$1" RM)" == 1 || "$(blk_field "$1" TRAN)" == usb ]]
|
||||
}
|
||||
|
||||
# Required commands.
|
||||
REQUIRED=(lsblk dd sync wipefs blockdev mount umount awk)
|
||||
missing=()
|
||||
for cmd in "${REQUIRED[@]}"; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || missing+=("$cmd")
|
||||
done
|
||||
if ((${#missing[@]})); then
|
||||
err "missing tools: ${missing[*]}"
|
||||
cat >&2 <<'EOF'
|
||||
# unsafe_reason DEVICE: if the device must not be written, print why and
|
||||
# return 0. Returns 1 (printing nothing) if it is acceptable.
|
||||
unsafe_reason() {
|
||||
local dev="$1" type mounts
|
||||
if ! is_block_device "$dev"; then
|
||||
printf '%s is not a block device\n' "$dev"; return 0
|
||||
fi
|
||||
if [[ -z "$(device_tree "$dev")" ]]; then
|
||||
printf 'cannot inspect %s with lsblk; refusing\n' "$dev"; return 0
|
||||
fi
|
||||
type="$(blk_field "$dev" TYPE)"
|
||||
if [[ "$type" != disk ]]; then
|
||||
printf '%s is not a whole disk (type: %s); pass the disk, not a partition\n' "$dev" "${type:-unknown}"
|
||||
return 0
|
||||
fi
|
||||
mounts="$(protected_mounts "$dev")"
|
||||
if [[ -n "$mounts" ]]; then
|
||||
printf '%s holds in-use system data (%s); refusing\n' "$dev" "$(tr '\n' ' ' <<<"$mounts" | sed 's/ $//')"
|
||||
return 0
|
||||
fi
|
||||
if ((! ALLOW_INTERNAL)) && ! is_external "$dev"; then
|
||||
printf '%s is neither removable nor on the USB bus; pass --allow-internal if you really mean it\n' "$dev"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# iso_on_device ISO DEVICE: true if the ISO file lives on the disk we're about to wipe.
|
||||
iso_on_device() {
|
||||
local src
|
||||
src="$(findmnt -n -o SOURCE --target "$1" 2>/dev/null || true)"
|
||||
src="${src%%\[*}"
|
||||
[[ -n "$src" ]] || return 1
|
||||
grep -qxF -- "$src" <<<"$(device_tree "$2")"
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Interactive pieces
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
select_device() {
|
||||
local -a cands=()
|
||||
mapfile -t cands < <(list_candidate_disks)
|
||||
((${#cands[@]})) || die "no candidate disks found" 4
|
||||
|
||||
log "Available whole disks:"
|
||||
printf ' %-3s %-14s %-9s %-6s %-12s %s\n' Idx Device Size Bus Kind Model >&2
|
||||
local i=0 d size bus model kind color
|
||||
for d in "${cands[@]}"; do
|
||||
i=$((i + 1))
|
||||
size="$(human "$(blockdev --getsize64 "$d" 2>/dev/null || echo 0)")"
|
||||
bus="$(blk_field "$d" TRAN)"
|
||||
model="$(blk_field "$d" MODEL)"
|
||||
if [[ -n "$(protected_mounts "$d")" ]]; then
|
||||
kind="SYSTEM DISK"; color="$C_RED"
|
||||
elif is_external "$d"; then
|
||||
kind="removable"; color="$C_GREEN"
|
||||
else
|
||||
kind="internal"; color="$C_YELLOW"
|
||||
fi
|
||||
printf ' %-3s %-14s %-9s %-6s %s%-12s%s %s\n' \
|
||||
"$i" "$d" "$size" "${bus:-?}" "$color" "$kind" "$C_RESET" "${model:-?}" >&2
|
||||
done
|
||||
echo >&2
|
||||
|
||||
local idx reason
|
||||
while :; do
|
||||
read -r -p "Select device [1-${#cands[@]}, 0 to abort]: " idx || die "unexpected end of input" 1
|
||||
[[ "$idx" =~ ^[0-9]{1,4}$ ]] || { warn "not a number"; continue; }
|
||||
idx=$((10#$idx)) # "08" is a number, not invalid octal
|
||||
((idx != 0)) || die "aborted by user" 1
|
||||
((idx <= ${#cands[@]})) || { warn "out of range"; continue; }
|
||||
if reason="$(unsafe_reason "${cands[idx - 1]}")"; then
|
||||
err "$reason"
|
||||
continue
|
||||
fi
|
||||
DEVICE="${cands[idx - 1]}"
|
||||
return 0
|
||||
done
|
||||
}
|
||||
|
||||
# describe_device DEVICE: "/dev/sdb (14.9GiB, SanDisk Ultra)"
|
||||
describe_device() {
|
||||
local model; model="$(blk_field "$1" MODEL)"
|
||||
printf '%s (%s%s)' "$1" "$(human "$DEV_BYTES")" "${model:+, $model}"
|
||||
}
|
||||
|
||||
resolve_device() {
|
||||
local reason
|
||||
if [[ -z "$DEVICE" ]]; then
|
||||
select_device
|
||||
else
|
||||
DEVICE="$(readlink -f -- "$DEVICE")" # /dev/disk/by-id/... -> /dev/sdX
|
||||
if reason="$(unsafe_reason "$DEVICE")"; then die "$reason" 4; fi
|
||||
fi
|
||||
DEV_BYTES="$(blockdev --getsize64 "$DEVICE")"
|
||||
log "Target: $(describe_device "$DEVICE")"
|
||||
if ((DEV_BYTES > 512 * 1024 * 1024 * 1024)); then
|
||||
warn "$DEVICE is larger than 512 GiB; that is unusual for a USB stick."
|
||||
fi
|
||||
}
|
||||
|
||||
# The invoking user's home, even under sudo (HOME may be /root there).
|
||||
invoking_home() {
|
||||
local h=""
|
||||
if [[ -n "${SUDO_USER:-}" ]] && command -v getent >/dev/null 2>&1; then
|
||||
h="$(getent passwd "$SUDO_USER" | cut -d: -f6)"
|
||||
fi
|
||||
printf '%s' "${h:-${HOME:-/}}"
|
||||
}
|
||||
|
||||
resolve_iso() {
|
||||
if [[ -z "$ISO_PATH" ]]; then
|
||||
local home; home="$(invoking_home)"
|
||||
while :; do
|
||||
read -r -e -p "Path to NixOS ISO: " ISO_PATH || die "unexpected end of input" 1
|
||||
ISO_PATH="${ISO_PATH/#\~/$home}"
|
||||
[[ -f "$ISO_PATH" ]] && break
|
||||
warn "not a file: $ISO_PATH"
|
||||
done
|
||||
fi
|
||||
[[ -f "$ISO_PATH" ]] || die "ISO not found: $ISO_PATH" 4
|
||||
ISO_BYTES="$(stat -c '%s' -- "$ISO_PATH")"
|
||||
((ISO_BYTES > 0)) || die "ISO is empty: $ISO_PATH" 4
|
||||
log "ISO: $ISO_PATH ($(human "$ISO_BYTES"))"
|
||||
|
||||
if command -v file >/dev/null 2>&1; then
|
||||
local ftype; ftype="$(file -b -- "$ISO_PATH")"
|
||||
if ! grep -qiE 'iso 9660|udf' <<<"$ftype"; then
|
||||
warn "$ftype"
|
||||
warn "file(1) doesn't recognize this as an ISO 9660 image. Continuing anyway."
|
||||
fi
|
||||
fi
|
||||
|
||||
((ISO_BYTES <= DEV_BYTES)) || die "ISO ($(human "$ISO_BYTES")) is larger than the disk ($(human "$DEV_BYTES"))" 4
|
||||
|
||||
if iso_on_device "$ISO_PATH" "$DEVICE"; then
|
||||
die "the ISO is stored on $DEVICE, which is about to be erased; copy it elsewhere first" 4
|
||||
fi
|
||||
|
||||
# Verify against a sha256 sidecar if there is one. Resolve symlinks so
|
||||
# `--iso iso/latest-...iso` finds the sidecar next to the real file.
|
||||
local real; real="$(readlink -f -- "$ISO_PATH")"
|
||||
if [[ -f "$real.sha256" ]]; then
|
||||
log "Verifying $real.sha256..."
|
||||
( cd -- "$(dirname -- "$real")" && sha256sum -c -- "$(basename -- "$real").sha256" >&2 ) \
|
||||
|| die "sha256 verification failed" 5
|
||||
else
|
||||
warn "no $(basename -- "$real").sha256 next to the ISO; skipping checksum verification"
|
||||
fi
|
||||
}
|
||||
|
||||
confirm_write() {
|
||||
cat >&2 <<EOF
|
||||
|
||||
${C_BOLD}About to:${C_RESET}
|
||||
${C_RED}WIPE${C_RESET} $(describe_device "$DEVICE")
|
||||
Write ISO $ISO_PATH
|
||||
|
||||
${C_YELLOW}All data on $DEVICE will be destroyed.${C_RESET}
|
||||
EOF
|
||||
if ((! ASSUME_YES)); then
|
||||
local typed
|
||||
read -r -p "Type the device path to confirm (e.g. $DEVICE): " typed || die "unexpected end of input" 1
|
||||
[[ "$typed" == "$DEVICE" ]] || die "confirmation didn't match; aborting" 1
|
||||
fi
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# The destructive part
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
unmount_all() {
|
||||
local pass mp mounts
|
||||
local -a mps
|
||||
log "Unmounting any partitions on $DEVICE..."
|
||||
for pass in 1 2 3 4; do # stacked mounts need more than one pass
|
||||
mounts="$(mounts_of "$DEVICE")" || die "could not read the mount table; refusing to write" 4
|
||||
mapfile -t mps <<<"$mounts"
|
||||
if [[ -z "$mounts" ]]; then return 0; fi
|
||||
((pass < 4)) || die "$DEVICE still has mounted filesystems: ${mps[*]}" 4
|
||||
for mp in "${mps[@]}"; do
|
||||
warn "umount $mp"
|
||||
# No lazy (-l) fallback: a lazily "unmounted" filesystem is still
|
||||
# live in the kernel and we'd be writing underneath it.
|
||||
umount -- "$mp" || die "could not unmount $mp; close whatever is using it and retry" 4
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
write_image() {
|
||||
log "Wiping signatures..."
|
||||
wipefs -a "$DEVICE" >/dev/null
|
||||
|
||||
log "Writing ISO with dd (this can take a few minutes)..."
|
||||
if ! dd if="$ISO_PATH" of="$DEVICE" bs=4M status=progress conv=fsync oflag=direct; then
|
||||
err "dd failed."
|
||||
# Surface recent kernel complaints so bad flash ("Medium Error") can be
|
||||
# told apart from a flaky cable/port ("reset", "Communication failure").
|
||||
local dev_short dmesg_out
|
||||
dev_short="$(basename -- "$DEVICE")"
|
||||
if dmesg_out="$(dmesg 2>/dev/null | grep -E "(${dev_short}|usb [0-9]+-[0-9]+)" | tail -10)" \
|
||||
&& [[ -n "$dmesg_out" ]]; then
|
||||
warn "Recent kernel messages mentioning ${dev_short} or USB events:"
|
||||
sed 's/^/ /' <<<"$dmesg_out" >&2
|
||||
warn "'Medium Error' / 'Hardware Error' => bad flash, replace the stick."
|
||||
warn "'reset' / 'Communication failure' => cable or port, try another."
|
||||
else
|
||||
warn "Run \`sudo dmesg | tail -30\` to see why the kernel rejected the write."
|
||||
fi
|
||||
exit 5
|
||||
fi
|
||||
|
||||
log "Final sync (flushing kernel buffers; may take a moment)..."
|
||||
sync
|
||||
blockdev --flushbufs "$DEVICE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
verify_write() {
|
||||
if ((! VERIFY)); then
|
||||
warn "skipping read-back verification (--no-verify)"
|
||||
return 0
|
||||
fi
|
||||
if ! command -v cmp >/dev/null 2>&1; then
|
||||
warn "cmp not found; skipping read-back verification"
|
||||
return 0
|
||||
fi
|
||||
log "Verifying: reading back $(human "$ISO_BYTES") from $DEVICE..."
|
||||
# flushbufs above also invalidated the device's page cache, so this reads
|
||||
# the stick itself rather than our own recent writes.
|
||||
if ! cmp -s -n "$ISO_BYTES" -- "$ISO_PATH" "$DEVICE"; then
|
||||
err "read-back verification FAILED: $DEVICE does not match the ISO."
|
||||
err "The stick is probably faulty or counterfeit (fake capacity). Don't trust it."
|
||||
exit 6
|
||||
fi
|
||||
log "Read-back verified."
|
||||
}
|
||||
|
||||
ensure_root() {
|
||||
((EUID == 0)) && return 0
|
||||
command -v sudo >/dev/null 2>&1 || die "must run as root and sudo is not installed" 1
|
||||
# Re-exec rather than ask the user to prefix the command, so both
|
||||
# `just make-usb` and `./scripts/make-usb.sh` just work. ${arr[@]+...}
|
||||
# expands safely under `set -u` even when there are no arguments.
|
||||
exec sudo --preserve-env=PATH -- "$BASH" "$SCRIPT_PATH" "${ORIG_ARGS[@]+"${ORIG_ARGS[@]}"}"
|
||||
}
|
||||
|
||||
main() {
|
||||
ORIG_ARGS=("$@")
|
||||
parse_args "$@"
|
||||
ensure_root
|
||||
|
||||
# Anything we still need to ask requires a terminal.
|
||||
if { [[ -z "$DEVICE" || -z "$ISO_PATH" ]] || ((! ASSUME_YES)); } && [[ ! -t 0 ]]; then
|
||||
die "stdin is not a tty; pass --iso, --device, and --yes for non-interactive use" 2
|
||||
fi
|
||||
|
||||
local missing=() cmd
|
||||
for cmd in lsblk findmnt dd sync wipefs blockdev umount awk stat tr sed grep; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || missing+=("$cmd")
|
||||
done
|
||||
if ((${#missing[@]})); then
|
||||
err "missing tools: ${missing[*]}"
|
||||
cat >&2 <<'EOF'
|
||||
|
||||
On NixOS / with Nix installed, re-run inside a shell that has them:
|
||||
nix shell nixpkgs#util-linux nixpkgs#coreutils -c sudo ./scripts/make-usb.sh
|
||||
@@ -85,211 +426,27 @@ On NixOS / with Nix installed, re-run inside a shell that has them:
|
||||
On Debian/Ubuntu:
|
||||
sudo apt install util-linux coreutils
|
||||
EOF
|
||||
exit 3
|
||||
fi
|
||||
exit 3
|
||||
fi
|
||||
|
||||
resolve_device
|
||||
resolve_iso
|
||||
confirm_write
|
||||
unmount_all
|
||||
write_image
|
||||
verify_write
|
||||
|
||||
|
||||
human() { numfmt --to=iec --suffix=B "$1" 2>/dev/null || echo "$1"; }
|
||||
|
||||
is_removable() {
|
||||
# /sys/block/<name>/removable: 1 = removable (USB stick, SD via USB reader),
|
||||
# 0 = fixed (internal disk, many "USB" enclosures lie though).
|
||||
local name; name="$(basename "$1")"
|
||||
[[ "$(cat "/sys/block/$name/removable" 2>/dev/null || echo 0)" == "1" ]]
|
||||
echo >&2
|
||||
log "${C_BOLD}Done.${C_RESET} You can unplug $DEVICE now."
|
||||
echo >&2
|
||||
info "Boot the new machine from this USB. Once at the installer shell:"
|
||||
info " - Connect to the network (Ethernet, or 'nmtui' on the graphical ISO)."
|
||||
info " - Clone your repo: git clone <your-repo-url> /tmp/notfiles"
|
||||
info " - Partition the target disk and mount it at /mnt, then:"
|
||||
info " nixos-install --flake /tmp/notfiles#<hostname>"
|
||||
}
|
||||
|
||||
contains_root_or_boot() {
|
||||
# Refuse if any partition on this disk holds /, /boot, or active swap.
|
||||
local dev="$1"
|
||||
lsblk -lnpo MOUNTPOINT,NAME "$dev" | awk -v d="$dev" '
|
||||
$1=="/" || $1=="/boot" || $1=="[SWAP]" { found=1 }
|
||||
END { exit !found }
|
||||
'
|
||||
}
|
||||
|
||||
select_device() {
|
||||
log "Available whole disks:"
|
||||
printf ' %-3s %-14s %-8s %-6s %-16s %s\n' "Idx" "Device" "Size" "Bus" "Removable" "Model"
|
||||
|
||||
# Use lsblk's pairs mode for robust parsing (handles spaces in MODEL).
|
||||
# lsblk -P emits lines of KEY="value" KEY="value" ... we sanity-check
|
||||
# the line matches that strict shape before eval'ing it.
|
||||
local -a CANDS=()
|
||||
local line NAME SIZE MODEL TRAN RM TYPE
|
||||
while IFS= read -r line; do
|
||||
[[ "$line" =~ ^([A-Z]+=\"[^\"]*\"[[:space:]]*)+$ ]] || continue
|
||||
NAME=""; SIZE=""; MODEL=""; TRAN=""; RM=""; TYPE=""
|
||||
eval "$line"
|
||||
[[ "${TYPE:-}" == "disk" ]] || continue
|
||||
# Skip optical, loop, ram, zram, dm.
|
||||
case "$NAME" in
|
||||
/dev/sr*|/dev/loop*|/dev/ram*|/dev/zram*|/dev/dm-*) continue ;;
|
||||
esac
|
||||
CANDS+=("$NAME"$'\t'"${SIZE:-?}"$'\t'"${TRAN:-?}"$'\t'"${RM:-0}"$'\t'"${MODEL:-?}")
|
||||
done < <(lsblk -dpP -o NAME,SIZE,MODEL,TRAN,RM,TYPE)
|
||||
|
||||
((${#CANDS[@]})) || die "no candidate disks found" 4
|
||||
|
||||
local i=1
|
||||
for c in "${CANDS[@]}"; do
|
||||
IFS=$'\t' read -r n s t r m <<<"$c"
|
||||
local marker=""
|
||||
if [[ "$r" == "1" ]]; then marker="${GREEN}yes${RESET}"; else marker="${YELLOW}no${RESET}"; fi
|
||||
if contains_root_or_boot "$n"; then
|
||||
marker="${RED}SYSTEM DISK${RESET}"
|
||||
fi
|
||||
printf ' %-3s %-14s %-8s %-6s %-16b %s\n' "$i" "$n" "$s" "$t" "$marker" "$m"
|
||||
((i++))
|
||||
done
|
||||
echo
|
||||
echo "Enter 0 to abort."
|
||||
echo
|
||||
|
||||
local idx
|
||||
while :; do
|
||||
read -r -p "Select device [1-${#CANDS[@]}]: " idx
|
||||
[[ "$idx" =~ ^[0-9]+$ ]] || { warn "not a number"; continue; }
|
||||
(( idx == 0 )) && die "aborted by user" 1
|
||||
(( idx >= 1 && idx <= ${#CANDS[@]} )) || { warn "out of range"; continue; }
|
||||
IFS=$'\t' read -r n _ _ r _ <<<"${CANDS[idx-1]}"
|
||||
if contains_root_or_boot "$n"; then
|
||||
err "$n is the running system disk — refusing"; continue
|
||||
fi
|
||||
if [[ "$r" != "1" ]] && (( ! ALLOW_INTERNAL )); then
|
||||
err "$n is not removable; pass --allow-internal if you really mean it"
|
||||
continue
|
||||
fi
|
||||
DEVICE="$n"
|
||||
return 0
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
|
||||
if [[ -z "$DEVICE" ]]; then
|
||||
select_device
|
||||
else
|
||||
[[ -b "$DEVICE" ]] || die "$DEVICE is not a block device" 2
|
||||
# Reject partitions. We want whole disks only.
|
||||
if [[ "$(lsblk -dno TYPE "$DEVICE" 2>/dev/null)" != "disk" ]]; then
|
||||
die "$DEVICE is not a whole disk (partition or other type)" 4
|
||||
fi
|
||||
if contains_root_or_boot "$DEVICE"; then
|
||||
die "$DEVICE holds /, /boot, or active swap — refusing" 4
|
||||
fi
|
||||
if ! is_removable "$DEVICE" && (( ! ALLOW_INTERNAL )); then
|
||||
die "$DEVICE is not removable; pass --allow-internal to override" 4
|
||||
fi
|
||||
# Run main only when executed, not when sourced (the tests source this file).
|
||||
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
|
||||
main "$@"
|
||||
fi
|
||||
|
||||
DEV_BYTES="$(blockdev --getsize64 "$DEVICE")"
|
||||
log "Target: $DEVICE ($(human "$DEV_BYTES"))"
|
||||
|
||||
|
||||
|
||||
if [[ -z "$ISO_PATH" ]]; then
|
||||
while :; do
|
||||
read -r -e -p "Path to NixOS ISO: " ISO_PATH
|
||||
ISO_PATH="${ISO_PATH/#\~/$HOME}"
|
||||
[[ -f "$ISO_PATH" ]] && break
|
||||
warn "not a file: $ISO_PATH"
|
||||
done
|
||||
fi
|
||||
[[ -f "$ISO_PATH" ]] || die "ISO not found: $ISO_PATH" 2
|
||||
|
||||
ISO_BYTES="$(stat -c '%s' "$ISO_PATH")"
|
||||
log "ISO: $ISO_PATH ($(human "$ISO_BYTES"))"
|
||||
|
||||
# Sanity: file should look like an ISO 9660 image.
|
||||
if command -v file >/dev/null 2>&1; then
|
||||
if ! file -b "$ISO_PATH" | grep -qiE 'iso 9660|udf'; then
|
||||
warn "$(file -b "$ISO_PATH")"
|
||||
warn "file(1) doesn't recognise this as ISO 9660. Continuing anyway."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Sanity: ISO must fit on disk.
|
||||
if (( ISO_BYTES > DEV_BYTES )); then
|
||||
die "ISO is larger than the disk" 4
|
||||
fi
|
||||
|
||||
# Optional sha256 sidecar verification.
|
||||
# Resolve through symlinks so `make-usb --iso iso/latest-...iso` finds
|
||||
# the sidecar that lives next to the real file.
|
||||
ISO_REAL="$(readlink -f "$ISO_PATH")"
|
||||
if [[ -f "$ISO_REAL.sha256" ]]; then
|
||||
log "Verifying $ISO_REAL.sha256..."
|
||||
( cd "$(dirname "$ISO_REAL")" && sha256sum -c "$(basename "$ISO_REAL").sha256" ) \
|
||||
|| die "sha256 verification failed" 5
|
||||
elif [[ -f "$ISO_PATH.sha256" ]]; then
|
||||
log "Verifying $ISO_PATH.sha256..."
|
||||
( cd "$(dirname "$ISO_PATH")" && sha256sum -c "$(basename "$ISO_PATH").sha256" ) \
|
||||
|| die "sha256 verification failed" 5
|
||||
fi
|
||||
|
||||
|
||||
|
||||
cat <<EOF
|
||||
|
||||
${BOLD}About to:${RESET}
|
||||
${RED}WIPE${RESET} $DEVICE ($(human "$DEV_BYTES"))
|
||||
Write ISO $ISO_PATH
|
||||
|
||||
${YELLOW}All data on $DEVICE will be destroyed.${RESET}
|
||||
EOF
|
||||
|
||||
if (( ! ASSUME_YES )); then
|
||||
read -r -p "Type the device path to confirm (e.g. $DEVICE): " typed
|
||||
[[ "$typed" == "$DEVICE" ]] || die "confirmation didn't match — aborting" 1
|
||||
fi
|
||||
|
||||
|
||||
|
||||
log "Unmounting any partitions on $DEVICE..."
|
||||
while read -r part mnt; do
|
||||
[[ -n "$mnt" ]] || continue
|
||||
warn "umount $part ($mnt)"
|
||||
umount "$part" 2>/dev/null || umount -l "$part" 2>/dev/null || warn "could not umount $part"
|
||||
done < <(lsblk -lnpo NAME,MOUNTPOINT "$DEVICE" | awk '$2!=""')
|
||||
|
||||
|
||||
|
||||
log "Wiping signatures..."
|
||||
wipefs -a "$DEVICE" >/dev/null
|
||||
|
||||
log "Writing ISO with dd (this can take a few minutes)..."
|
||||
if ! dd if="$ISO_PATH" of="$DEVICE" bs=4M status=progress conv=fsync oflag=direct; then
|
||||
err "dd failed."
|
||||
# Surface the most recent kernel complaints about this device so the
|
||||
# user can distinguish bad-block / hardware failure ("Medium Error",
|
||||
# "Hardware Error") from cable/port flakiness ("usb ... reset",
|
||||
# "Communication failure") without having to dig through dmesg.
|
||||
dev_short="$(basename "$DEVICE")"
|
||||
if dmesg_out="$(dmesg 2>/dev/null | grep -E "(${dev_short}|usb [0-9]+-[0-9]+)" | tail -10)" \
|
||||
&& [[ -n "$dmesg_out" ]]; then
|
||||
warn "Recent kernel messages mentioning ${dev_short} or USB events:"
|
||||
printf '%s\n' "$dmesg_out" | sed 's/^/ /' >&2
|
||||
warn "Look for 'Medium Error' / 'Hardware Error' (bad flash → replace stick),"
|
||||
warn "or 'reset' / 'Communication failure' (cable/port → try a different one)."
|
||||
else
|
||||
warn "Run \`sudo dmesg | tail -30\` to see why the kernel rejected the write."
|
||||
fi
|
||||
exit 5
|
||||
fi
|
||||
|
||||
log "Final sync (flushing kernel buffers; may take a moment)..."
|
||||
sync
|
||||
blockdev --flushbufs "$DEVICE" 2>/dev/null || true
|
||||
|
||||
|
||||
|
||||
echo
|
||||
log "${BOLD}Done.${RESET} You can unplug $DEVICE now."
|
||||
echo
|
||||
info "Boot the new machine from this USB. Once at the installer shell:"
|
||||
info " - Connect to the network (Ethernet, or 'sudo systemctl start wpa_supplicant' + 'wpa_cli', or 'nmtui' on the graphical ISO)."
|
||||
info " - Clone your repo: git clone <your-repo-url> /tmp/notfiles"
|
||||
info " - Partition the target disk, mount at /mnt, then:"
|
||||
info " nixos-install --flake /tmp/notfiles#<hostname>"
|
||||
echo
|
||||
Reference in new issue
Block a user