#!/usr/bin/env bash # reroot: reinstall Debian/Ubuntu from a rescue system onto a software RAID of the disks you choose. # Usage: curl -fsSL reroot.run | bash -s -- [options] (see --help) # # Copyright (C) 2026 MadMakz # SPDX-License-Identifier: AGPL-3.0-only # # This program is free software: you can redistribute it and/or modify it under the terms of the # GNU Affero General Public License as published by the Free Software Foundation, version 3 of the # License. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License along with this program. # If not, see . set -Eeuo pipefail VERSION=1.0-alpha1 # set on release; shown as the dialog title # Defaults; options and menus change them. defaults() { TARGET=/mnt/reroot WORK=/tmp/reroot DEB_POOL=https://deb.debian.org/debian/pool/main CACHE_RAM_SIZE=3G # tmpfs cap for the package cache (peak measured: see cache_in_ram) CACHE_RAM_MIN_MB=4096 # only use RAM when this much is available OS=debian-13 LEVEL=1 DISKS=() ROOT_SIZE= HOME_PART=0 HOME_SIZE= DATA_SIZE= # Proxmox: the thin pool for VM disks (empty = rest) SWAP_SIZE= BOOT_SIZE=2G ESP_SIZE=512M SMALLEST_BYTES=0 # smallest chosen disk, set by step_level ZERO_OTHERS=0 # also erase the RAID superblock of old arrays' members on unchosen disks LVM=0 VG=vg0 ZFS=0 # root on ZFS: pools bpool (/boot) and rpool instead of md arrays (swap stays md) ZFS_SIZE= # rpool's partition per disk (empty = rest) HOSTNAME_NEW=reroot NET_PEER= # point-to-point peer of the first IPv4 address (ifupdown's "pointopoint") NET_CUSTOM=0 KEYMAP= LOCALE= NET_DHCP=0 SSH_KEYS=() SSH=1 SSH_PASSWORD=1 USER_NEW= DISABLE_ROOT=0 ROOT_PW= USER_PW= # command apt dnf apk pacman DEPS=" sgdisk gdisk gdisk sgdisk gptfdisk mdadm mdadm mdadm mdadm mdadm lvm lvm2 lvm2 lvm2 lvm2 dmsetup dmsetup device-mapper device-mapper device-mapper wipefs util-linux util-linux util-linux util-linux mkfs.ext4 e2fsprogs e2fsprogs e2fsprogs e2fsprogs mkfs.vfat dosfstools dosfstools dosfstools dosfstools efibootmgr efibootmgr efibootmgr efibootmgr efibootmgr curl curl curl curl curl wget wget wget wget wget ar binutils binutils binutils binutils perl perl perl perl perl gpgv gpgv gnupg2 gpgv gnupg xz xz-utils xz xz xz zstd zstd zstd zstd zstd dialog dialog dialog dialog dialog numfmt coreutils coreutils coreutils coreutils ip iproute2 iproute iproute2 iproute2 " } defaults log() { printf '\033[1;32m==>\033[0m %s\n' "$*" >&2; } warn() { printf '\033[1;33mWARNING:\033[0m %s\n' "$*" >&2; } die() { printf '\033[1;31mERROR:\033[0m %s\n' "$*" >&2; exit 1; } usage() { cat <<'EOF' reroot: install Debian/Ubuntu onto software RAID from a Linux rescue system. Usage: reroot.sh [options] Everything is chosen in menus: disks, RAID level, system, hostname, layout, network, user, SSH and passwords. The options below only preselect menu values. /boot is always RAID 1 across all chosen disks; /, /home and swap use the chosen level. With a single disk chosen, everything goes onto it without RAID. --os OS distributions: debian-12, debian-13 (default), ubuntu-24.04, ubuntu-26.04 platforms: proxmox-9 (Proxmox VE 9 on Debian 13, experimental) --root-size SIZE / partition size per disk, e.g. 50G (default: rest of disk, or 50G with --home) --home separate /home (default size: rest of disk) --home-size SIZE /home partition size per disk; implies --home. Space after the last partition stays unpartitioned --swap SIZE add swap, SIZE per disk --lvm LVM on the RAID: /, /home and swap become volumes in vg0 that can grow later; sizes are then totals, not per disk --zfs root on ZFS (experimental): /boot in pool bpool, / (and --home) as datasets in pool rpool, where --root-size/--home-size are limits (quotas); swap stays on md RAID. ZFS is installed on the rescue system if it's missing (after asking) --pool-size SIZE ZFS: rpool partition size per disk (default: rest of disk) --boot-size SIZE /boot partition size per disk (default 2G; no menu) --hostname NAME default: reroot --keymap LAYOUT keyboard layout (XKB name: us, de, fr, ...; default: the rescue's) --locale LOCALE e.g. en_US.UTF-8, de_DE.UTF-8, C.UTF-8 (default: the rescue's, or en_US.UTF-8 when the rescue only runs C) --dhcp network by DHCP (preselected anyway when the rescue got its address by DHCP; otherwise static, copied from the rescue) --user NAME create a user with sudo rights --disable-root lock root's password and forbid root SSH login (needs --user; not with proxmox-9, whose web interface logs in as root) --ssh-key KEY authorized key, as a key line or a file; repeatable. Goes to root and the --user account. Default: the rescue's /root/.ssh/authorized_keys. The SSH menu can add one more. --ssh-keys-only SSH login with keys only (default: password or key) --no-ssh don't install the SSH server (console access only) -h, --help Sizes are per-disk partition sizes (M, G or T); usable space depends on the RAID level. EOF } parse_args() { while (($#)); do case $1 in --os) OS=${2:?--os needs a value}; shift ;; --root-size) ROOT_SIZE=${2:?--root-size needs a value}; shift ;; --home) HOME_PART=1 ;; --home-size) HOME_PART=1 HOME_SIZE=${2:?--home-size needs a value}; shift ;; --swap) SWAP_SIZE=${2:?--swap needs a value}; shift ;; --lvm) LVM=1 ;; --zfs) ZFS=1 ;; --pool-size) ZFS_SIZE=${2:?--pool-size needs a value}; shift ;; --boot-size) BOOT_SIZE=${2:?--boot-size needs a value}; shift ;; --hostname) HOSTNAME_NEW=${2:?--hostname needs a value}; shift ;; --keymap) KEYMAP=${2:?--keymap needs a value}; shift ;; --locale) LOCALE=${2:?--locale needs a value}; shift ;; --dhcp) NET_DHCP=1 ;; --ssh-key) SSH_KEYS+=("${2:?--ssh-key needs a value}"); shift ;; --ssh-keys-only) SSH_PASSWORD=0 ;; --no-ssh) SSH=0 ;; --user) USER_NEW=${2:?--user needs a value}; shift ;; --disable-root) DISABLE_ROOT=1 ;; -h | --help) usage; exit 0 ;; *) die "unknown option: $1 (see --help)" ;; esac shift done if ((HOME_PART && !ZFS)) && [[ -z $ROOT_SIZE ]]; then ROOT_SIZE=50G; fi # ZFS: sizes are limits local s for s in "$ROOT_SIZE" "$HOME_SIZE" "$SWAP_SIZE" "$BOOT_SIZE" "$ZFS_SIZE"; do [[ -z $s ]] || valid_size "$s" || die "invalid size: $s (use e.g. 512M, 50G, 2T)" done valid_hostname "$HOSTNAME_NEW" || die "invalid hostname: $HOSTNAME_NEW" [[ -z $KEYMAP ]] || valid_keymap "$KEYMAP" || die "invalid keymap: $KEYMAP (an XKB layout such as us, de, fr)" [[ -z $LOCALE ]] || valid_locale "$LOCALE" || die "invalid locale: $LOCALE (e.g. en_US.UTF-8, C.UTF-8)" valid_user "$USER_NEW" || die "invalid user name: $USER_NEW" if ((DISABLE_ROOT)) && [[ -z $USER_NEW ]]; then die "--disable-root needs --user, or nobody could log in"; fi set_os || die "unsupported --os: $OS (use debian-12, debian-13, ubuntu-24.04, ubuntu-26.04 or proxmox-9)" if ((DISABLE_ROOT && PVE)); then die "--disable-root: Proxmox VE's web interface logs in as root"; fi if ((LVM && ZFS)); then die "--lvm or --zfs, not both"; fi } valid_size() { [[ $1 =~ ^[1-9][0-9]*[MGT]$ ]]; } valid_size_or_rest() { [[ -z $1 ]] || valid_size "$1"; } valid_hostname() { [[ $1 =~ ^[A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$ ]]; } # Empty = no user. Not a name the new system already has as a user or group (Debian's base-passwd, # systemd, the installed packages): useradd would fail there, after the disks are wiped. valid_user() { [[ -z $1 ]] && return [[ $1 =~ ^[a-z_][a-z0-9_-]{0,31}$ && $1 != _* && $1 != systemd-* ]] || return 1 ! [[ " root daemon bin sys sync games man lp mail news uucp proxy www-data backup list irc gnats nobody adm tty disk kmem dialout fax voice cdrom floppy tape sudo audio dip operator src shadow utmp video sasl plugdev staff users nogroup input kvm render sgx clock netdev crontab messagebus sshd polkitd tss uuidd postfix postdrop syslog " =~ [[:space:]]"$1"[[:space:]] ]] } valid_ip4() { local o [[ $1 =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1 IFS=. read -ra o <<<"$1" ((10#${o[0]} <= 255 && 10#${o[1]} <= 255 && 10#${o[2]} <= 255 && 10#${o[3]} <= 255)) } valid_ip6() { [[ $1 =~ ^[0-9a-fA-F:]+$ && $1 =~ [0-9a-fA-F] && $1 == *:*:* ]]; } # loose: hex groups and colons valid_cidr4() { [[ $1 =~ /([0-9]{1,2})$ ]] && ((10#${BASH_REMATCH[1]} <= 32)) && valid_ip4 "${1%/*}"; } valid_cidr6() { [[ $1 =~ /([0-9]{1,3})$ ]] && ((10#${BASH_REMATCH[1]} <= 128)) && valid_ip6 "${1%/*}"; } valid_ip4_opt() { [[ -z $1 ]] || valid_ip4 "$1"; } valid_ip6_opt() { [[ -z $1 ]] || valid_ip6 "$1"; } valid_cidr4_opt() { [[ -z $1 ]] || valid_cidr4 "$1"; } valid_cidr6_opt() { [[ -z $1 ]] || valid_cidr6 "$1"; } valid_dns() { local d list read -ra list <<<"$1" ((${#list[@]})) || return 1 for d in "${list[@]}"; do valid_ip4 "$d" || valid_ip6 "$d" || return 1; done } valid_keymap() { [[ $1 =~ ^[a-z]{2,8}$ ]]; } # XKB layout name valid_locale() { [[ $1 == C.UTF-8 || $1 =~ ^[a-z]{2,3}_[A-Z]{2}\.UTF-8$ ]]; } # conf_value FILE VAR: value of VAR= in a shell-style config file, quotes stripped. conf_value() { local line [[ -r $1 ]] || return 0 while IFS= read -r line; do if [[ $line =~ ^[[:space:]]*$2=[\"\']?([^\"\']*) ]]; then echo "${BASH_REMATCH[1]}" return fi done <"$1" } # Console keymap name (vconsole.conf, loadkeys) to XKB layout: de-latin1-nodeadkeys -> de, uk -> gb. xkb_layout() { local l=${1%%-*} l=${l%%_*} if [[ $l == uk ]]; then l=gb; fi echo "$l" } # Preselect the rescue's keyboard and language, so the new system matches what you type on now. detect_locale_keymap() { local v if [[ -z $KEYMAP ]]; then v=$(conf_value /etc/default/keyboard XKBLAYOUT) v=${v%%,*} if [[ -z $v ]]; then v=$(conf_value /etc/vconsole.conf KEYMAP); fi if [[ -z $v ]] && command -v localectl >/dev/null; then # localectl fails without a running systemd/dbus (containers, some rescues): just no value. v=$({ localectl status 2>/dev/null || true; } | awk -F': *' '!v && /X11 Layout|VC Keymap/ && $2 != "n/a" {v = $2} END {print v}') fi KEYMAP=$(xkb_layout "${v:-us}") valid_keymap "$KEYMAP" || KEYMAP=us fi if [[ -z $LOCALE ]]; then v=$(conf_value /etc/locale.conf LANG) if [[ -z $v ]]; then v=$(conf_value /etc/default/locale LANG); fi v=${v/.utf8/.UTF-8} # A rescue running plain C/POSIX says nothing about the language you want. if valid_locale "$v" && [[ $v != C.UTF-8 ]]; then LOCALE=$v; else LOCALE=en_US.UTF-8; fi fi } set_os() { PVE=0 case $OS in debian-12) DISTRO=debian SUITE=bookworm MIRROR=http://deb.debian.org/debian ZFS_COMPAT=openzfs-2.1-linux ;; debian-13) DISTRO=debian SUITE=trixie MIRROR=http://deb.debian.org/debian ZFS_COMPAT=openzfs-2.3-linux ;; proxmox-9) DISTRO=debian SUITE=trixie MIRROR=http://deb.debian.org/debian ZFS_COMPAT=openzfs-2.3-linux PVE=1 ;; ubuntu-24.04) DISTRO=ubuntu SUITE=noble MIRROR=http://archive.ubuntu.com/ubuntu ZFS_COMPAT=openzfs-2.2-linux ;; ubuntu-26.04) DISTRO=ubuntu SUITE=resolute MIRROR=http://archive.ubuntu.com/ubuntu ZFS_COMPAT=openzfs-2.4-linux ;; *) return 1 ;; esac # ZFS: the root dataset (Proxmox's installer calls it pve-1). ZFS_COMPAT is the target's OpenZFS # release: a newer rescue would otherwise create a pool with features the target can't import. ZFS_ROOT=rpool/ROOT/$DISTRO if ((PVE)); then ZFS_ROOT=rpool/ROOT/pve-1; fi } min_disks() { case $1 in 0 | 1) echo 2 ;; 5) echo 3 ;; 6 | 10) echo 4 ;; *) return 1 ;; esac } # Partition plan, identical on every disk, as name:size (size 0 = rest of disk). VOLS are the # filesystems after /boot: partitions of their own, or with LVM volumes on one lvm partition. # With ZFS, boot is bpool's partition, zfs rpool's, and VOLS only swap: datasets have no sizes. plan_partitions() { # Proxmox: LVM (or ZFS), with VM disks in a thin pool (or dataset) instead of /home, like its # own installer. ZFS: a separate /home is a dataset, not a partition. if ((PVE && !ZFS)); then LVM=1; fi if ((PVE)); then HOME_PART=0; fi if ((ZFS)); then LVM=0; fi VOLS=() if [[ $SWAP_SIZE ]]; then VOLS+=("swap:$SWAP_SIZE"); fi PARTS=(bios:1M "esp:$ESP_SIZE" "boot:$BOOT_SIZE") if ((ZFS)); then PARTS+=("${VOLS[@]}" "zfs:${ZFS_SIZE:-0}") return fi VOLS+=("root:${ROOT_SIZE:-0}") if ((HOME_PART)); then VOLS+=("home:${HOME_SIZE:-0}"); fi if ((PVE)); then VOLS+=("data:${DATA_SIZE:-0}"); fi if ((LVM)); then PARTS+=(lvm:0); else PARTS+=("${VOLS[@]}"); fi } # ZFS's name for a RAID level's layout. zfs_kind() { case $1 in 0) echo stripe ;; 1) echo mirror ;; 5) echo raidz1 ;; 6) echo raidz2 ;; 10) echo "striped mirrors" ;; esac; } # vdev LEVEL DEV...: zpool create's vdev words for the level, one per line. 10 = mirrored pairs. vdev() { local level=$1 shift if (($# == 1 || level == 0)); then printf '%s\n' "$@" elif ((level == 10)); then while (($#)); do printf '%s\n' mirror "$1" "$2" shift 2 done else printf '%s\n' "$(zfs_kind "$level")" "$@" fi } # One chosen disk: no RAID, the filesystems (or LVM) go straight onto its partitions. single() { ((${#DISKS[@]} == 1)); } # Block device of a filesystem (or of the lvm PV): its md array, its partition on a single disk, # or with LVM its volume (/boot is never on LVM). vol() { if ((LVM)) && [[ $1 != boot && $1 != lvm ]]; then echo "/dev/$VG/$1" elif single; then part "${DISKS[0]}" "$1" else echo "/dev/md/$1" fi } size_bytes() { numfmt --from=iec "$1"; } # 50G -> bytes; sgdisk also reads M/G/T as MiB/GiB/TiB # sum_bytes NAME:SIZE...: their bytes, counting at least 1G for a size 0 (the rest). sum_bytes() { local p sum=0 for p; do if [[ ${p#*:} == 0 ]]; then sum=$((sum + (1 << 30))); else sum=$((sum + $(size_bytes "${p#*:}"))); fi done echo "$sum" } # Bytes per disk the partitions need, plus 2 MiB for the GPT and alignment. layout_bytes() { plan_partitions echo $(($(sum_bytes "${PARTS[@]}") + (2 << 20))) } # About what the LVM volume group will hold: the smallest disk's lvm partition minus mdadm's data # offset (up to 128 MiB), at the chosen RAID level, minus 1 MiB of LVM metadata. vg_bytes() { local part=$((SMALLEST_BYTES - $(layout_bytes) + (1 << 30) - (128 << 20))) echo $(($(usable_bytes "$LEVEL" ${#DISKS[@]} "$part") - (1 << 20))) } # About what rpool holds: its partition on the smallest disk at the chosen level, minus the 1/32 # ZFS keeps in reserve (slop space). rpool_bytes() { local part b if [[ $ZFS_SIZE ]]; then part=$(size_bytes "$ZFS_SIZE") else part=$((SMALLEST_BYTES - $(layout_bytes) + (1 << 30))) # layout_bytes counts the rest as 1G fi b=$(usable_bytes "$LEVEL" ${#DISKS[@]} "$part") echo $((b - b / 32)) } # A dataset's limit: empty (none), or a size rpool can hold. valid_zfs_limit() { [[ -z $1 ]] || { valid_size "$1" && (($(size_bytes "$1") <= $(rpool_bytes))); }; } part_no() { local i for i in "${!PARTS[@]}"; do if [[ ${PARTS[i]%%:*} == "$1" ]]; then echo $((i + 1)); return; fi done return 1 } part() { echo "$1-part$(part_no "$2")"; } # Stable /dev/disk/by-id name for a whole disk; prefers model/serial names over wwn/eui. by_id() { local dev link fallback= dev=$(readlink -f "$1") for link in /dev/disk/by-id/*; do [[ $link != *-part* && $(readlink -f "$link") == "$dev" ]] || continue case ${link##*/} in wwn-* | nvme-eui.* | nvme-nvme.*) fallback=${fallback:-$link} ;; *) echo "$link"; return ;; esac done [[ $fallback ]] || die "no /dev/disk/by-id link for $1" echo "$fallback" } # Changes to the rescue system are listed and confirmed first; nothing happens on "n". preflight() { ((EUID == 0)) || die "run as root" [[ $(uname -m) == x86_64 ]] || die "only x86_64 is supported for now" if [[ -d /sys/firmware/efi ]]; then UEFI=1; else UEFI=0; fi find_deps local m mods=() efivars=0 leftover=0 plan=() pools=() for m in md_mod raid0 raid1 raid456 raid10 dm_mod; do if [[ ! -d /sys/module/$m ]] && ! grep -qs "/$m\.ko" "/lib/modules/$(uname -r)/modules.builtin"; then mods+=("$m") fi done if ((UEFI)) && ! mountpoint -q /sys/firmware/efi/efivars; then efivars=1; fi if mountpoint -q "$TARGET"; then leftover=1; fi if command -v zpool >/dev/null; then mapfile -t pools < <({ zpool list -Ho name,altroot 2>/dev/null || true; } | awk -v t="$TARGET" '$2 == t {print $1}') fi if ((${#PKGS[@]})); then plan+=("install ${PKGS[*]} with $PM (for ${MISSING[*]})"); fi if ((${#mods[@]})); then plan+=("load kernel modules: ${mods[*]}"); fi if ((efivars)); then plan+=("mount efivarfs on /sys/firmware/efi/efivars (UEFI boot entries)"); fi if ((leftover)); then plan+=("unmount $TARGET, left mounted by an earlier run"); fi if ((${#pools[@]})); then plan+=("export ZFS pools ${pools[*]}, left imported by an earlier run"); fi if ((${#plan[@]})); then log "Before the menus, reroot needs to change this rescue system (no disk is touched):" printf ' - %s\n' "${plan[@]}" >&2 confirm "Go ahead?" || die "stopped; nothing was changed" fi install_deps for m in "${mods[@]}"; do modprobe "$m" 2>/dev/null || true; done grep -q '\[raid1\]' /proc/mdstat 2>/dev/null || die "kernel lacks md RAID 1 support" if ((efivars)); then mount -t efivarfs efivarfs /sys/firmware/efi/efivars; fi if ((leftover)); then umount -R "$TARGET"; fi if ((${#pools[@]})); then zpool export "${pools[@]}"; fi } # confirm QUESTION: y/n on the terminal, Enter = yes. confirm() { local a printf '\033[1;32m==>\033[0m %s [Y/n] ' "$1" >&2 # log's arrow, without its newline read -r a /dev/null; then break; fi done while read -r cmd apt dnf apk pac; do if [[ -z $cmd ]] || command -v "$cmd" >/dev/null; then continue; fi MISSING+=("$cmd") case $PM in apt-get) PKGS+=("$apt") ;; dnf) PKGS+=("$dnf") ;; apk) PKGS+=("$apk") ;; pacman) PKGS+=("$pac") ;; esac done <<<"$DEPS" # shortcut: no static-binary fallback yet; add one if a rescue without a package manager shows up. if ((${#MISSING[@]})) && [[ -z $PM ]]; then die "missing tools: ${MISSING[*]} (and no apt/dnf/apk/pacman to install them)" fi } install_deps() { local cmd ((${#MISSING[@]})) || return 0 log "installing rescue tools: ${PKGS[*]}" case $PM in apt-get) apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends "${PKGS[@]}" ;; dnf) dnf install -y "${PKGS[@]}" ;; apk) apk add "${PKGS[@]}" ;; pacman) pacman -Sy --noconfirm --needed "${PKGS[@]}" ;; esac /dev/null || die "still missing after install: $cmd"; done } # ZFS for the rescue system, which creates the pools. Runs as a condition (no set -e): every step # that can fail returns. install_zfs() { local pkgs=(zfsutils-linux) codename build=/usr/share/sysrescue/bin/build-zfs-srm case $PM in apt-get) apt-get update -qq || return # Debian keeps ZFS in contrib, which rescue systems rarely enable. madison lists only # installable versions; apt-cache show also succeeds for a name other packages mention. if [[ -z $(apt-cache madison zfsutils-linux 2>/dev/null) ]]; then codename=$(conf_value /etc/os-release VERSION_CODENAME) [[ $codename ]] || return echo "deb http://deb.debian.org/debian $codename contrib" >/etc/apt/sources.list.d/reroot-zfs.list apt-get update -qq || return fi # Ubuntu's kernels ship the module; otherwise DKMS builds it for the running kernel. if ! modinfo zfs >/dev/null 2>&1; then pkgs+=(zfs-dkms "linux-headers-$(uname -r)"); fi DEBIAN_FRONTEND=noninteractive apt-get install -y -q "${pkgs[@]}" ;; apk) apk add zfs "zfs-$(uname -r | sed 's/.*-//')" ;; # the kernel flavor's module: zfs-lts, zfs-virt pacman) # Arch has no ZFS packages. SystemRescue's own script builds them from the AUR and installs # them, the module by DKMS against headers from its pinned Arch snapshot (so they match its # kernel); it compiles in RAM (~4 GB). Other Arch-based rescues: no reliable source. if [[ ! -x $build ]]; then echo "ZFS on Arch-based rescue systems: only SystemRescue (its $build) is supported" return 1 fi # makepkg builds on one core unless MAKEFLAGS says otherwise (the module's DKMS build uses # all); the script resets its build user's environment, so a drop-in, read since pacman 7. mkdir -p /etc/makepkg.conf.d || return echo "MAKEFLAGS=\"-j$(nproc)\"" >/etc/makepkg.conf.d/reroot-jobs.conf || return "$build" || return rm -rf /tmp/zfsbuild # its build tree, GBs of RAM; the module is installed by now ;; *) echo "no ZFS packages known for this rescue system (package manager: ${PM:-none})" return 1 ;; esac /dev/null; then return 0; fi if ! command -v zpool >/dev/null || ! modinfo zfs >/dev/null 2>&1; then install=1 what="install ZFS with ${PM:-the package manager} (on Debian-based rescues a module build: a few minutes)" if [[ $PM == pacman ]]; then what="build ZFS with SystemRescue's build-zfs-srm (compiles in RAM, needs ~4 GB free: 20-40 minutes)" fi fi msg --title "ZFS" --yesno "The pools are created by this rescue system, which has no ZFS yet. To get it, reroot \ would ${what}.\n\nNo disk is touched. Go ahead?" 10 78 || return 1 # In the background, so the screen can show its output and the time so far: a module build # prints nothing but a growing row of dots for minutes. (if ((install)); then install_zfs || exit; fi; modprobe zfs && command -v zpool) "$log" 2>&1 & pid=$! start=$SECONDS while kill -0 "$pid" 2>/dev/null; do printf -v t '%d:%02d' $(((SECONDS - start) / 60)) $(((SECONDS - start) % 60)) msg --title "ZFS" --cr-wrap --no-collapse --infobox "Setting up ZFS in the rescue system, $t so far \ (log: $log):\n\n$(log_tail "$log" 14)" 20 78 sleep 2 done if wait "$pid"; then check_ram # the packages and the module took RAM: the package cache may not fit any more return 0 fi msg --title "ZFS" --cr-wrap --no-collapse --msgbox "ZFS could not be set up in this rescue system:\n\n$(log_tail "$log" 10)\n\n\ Choose another storage, or a rescue system with ZFS." 20 78 || true return 1 } # log_tail FILE N: a log's last N lines for a dialog box, without colors or carriage returns. Long # lines keep their end, where a growing row of dots shows a build is still going. log_tail() { tail -n "$2" "$1" | tr -d '\r' | sed 's/\x1b\[[0-9;?]*[a-zA-Z]//g' | awk '{if (length > 74) $0 = "..." substr($0, length - 70); print}' } # dialog on the terminal even under curl | bash; the selection is printed to stdout. Buttons: OK, # Back (exit 3), Quit (1; Esc: 255). msg is for message boxes, which only need OK. # Some terminals (PuTTY and the like) ignore the VT100 line-drawing charset and show borders as # lqqqk: under UTF-8 ncurses draws Unicode lines instead, otherwise dialog uses plain ASCII. msg() { local lines=(--ascii-lines) if [[ $(locale charmap 2>/dev/null || true) == UTF-8 ]]; then lines=(); fi NCURSES_NO_UTF8_ACS=1 dialog --backtitle "reroot $VERSION" "${lines[@]}" --insecure "$@" \ 3>&1 1>/dev/tty 2>&3 /dev/null || true; } # reads the disk itself, not udev's cache # Existing content on a disk, one line each; empty if the disk looks blank. disk_data() { local dev fs label label=$(probe PTTYPE "$1") if [[ $label ]]; then echo "$label partition table"; fi for dev in $(lsblk -lnpo NAME "$1"); do fs=$(probe TYPE "$dev") [[ $fs ]] || continue label=$(probe LABEL "$dev") echo "${dev##*/}: $fs${label:+ \"$label\"}, $(blk SIZE "$dev")" done } # level_options N SMALLEST_BYTES: dialog radiolist items for the levels N disks allow. # usable_bytes LEVEL N BYTES: size of an array of N members with BYTES each. usable_bytes() { case $1 in 0) echo $(($2 * $3)) ;; 1) echo "$3" ;; 5) echo $((($2 - 1) * $3)) ;; 6) echo $((($2 - 2) * $3)) ;; 10) echo $(($2 * $3 / 2)) ;; esac } # With ZFS the same levels by ZFS's names (raidz1 for RAID 5, ...); its RAID 10 is mirrored pairs, # so only for an even number of disks. level_options() { local n=$1 s=$2 l usable desc name want=$LEVEL if ((n < $(min_disks "$want"))) || ((ZFS && want == 10 && n % 2)); then want=1; fi for l in 1 0 5 6 10; do ((n >= $(min_disks "$l"))) || continue if ((ZFS && l == 10 && n % 2)); then continue; fi case $l in 1) desc="mirror, survives $((n - 1)) failed disk(s)" ;; 0) desc="stripe, NO redundancy" ;; 5) desc="parity, survives 1 failed disk" ;; 6) desc="double parity, survives 2 failed disks" ;; 10) desc="striped mirrors, survives 1 failed disk" ;; esac name="RAID $l" if ((ZFS)); then name=$(zfs_kind "$l") desc=${desc#*, } # the kind is the name now if ((l >= 5)); then name+=" (like RAID $l)"; fi fi usable=$(usable_bytes "$l" "$n" "$s") printf '%s\n%s\n%s\n' "$l" "$name: $desc, ~$(numfmt --to=iec "$usable") total" \ "$(on "$l" "$want")" done } step_disks() { local name mark state items=() sel cur=' ' d i why for d in "${DISKS[@]}"; do cur+="$(readlink -f "$d") "; done # the earlier choice, when coming back while read -r name; do mark='' state=OFF if [[ $(disk_data "/dev/$name") ]]; then mark=" [HAS DATA]"; fi if [[ $cur == *" /dev/$name "* ]]; then state=ON; fi items+=("$name" "$(disk_desc "/dev/$name")$mark" "$state") done < <(lsblk -dnbo NAME,TYPE,SIZE | awk '$2 == "disk" && $3 > 0 && $1 !~ /^(zram|ram)/ {print $1}') ((${#items[@]})) || die "no disks found" while :; do sel=$(tui --title "Disks" --separate-output --checklist \ "Choose the disks (space toggles, enter confirms): 2 or more for a RAID, 1 without RAID.\nEverything on them will be erased; other disks are not touched." \ 20 78 10 "${items[@]}") || { back $?; return 0; } mapfile -t DISKS < <(grep . <<<"$sel") if ((${#DISKS[@]} < 1)); then msg --title "Disks" --msgbox "Choose at least 1 disk." 8 40 || true continue fi for i in "${!DISKS[@]}"; do DISKS[i]=$(by_id "/dev/${DISKS[i]}"); done why=$(disks_busy) [[ $why ]] || break msg --title "Disks" --msgbox "$why" 10 78 || true done } # md_others: "ARRAY MEMBER DISK" for each member of an array on the chosen disks that lies on a # disk that wasn't chosen. Read while the arrays are still assembled. md_others() { local d md m x for d in "${DISKS[@]}"; do for md in $(lsblk -lnpo NAME,TYPE "$d" | awk '$2 ~ /^raid/ {print $1}'); do for m in "${SYSFS:-/sys}"/class/block/"${md##*/}"/slaves/*; do # SYSFS: the tests' fake [[ -e $m ]] || continue x=$(unchosen_disk "/dev/${m##*/}") if [[ $x ]]; then echo "$md /dev/${m##*/} $x"; fi done done done | sort -u } # Old arrays that also span unchosen disks lose only the chosen disks' members; the rest keep a # degraded copy, which the new system may assemble again. Erasing their superblock is opt-in. step_md_others() { local others list md m d v others=$(md_others) if [[ ! $others ]]; then ZERO_OTHERS=0 SKIP=1; return 0; fi while read -r md m d; do list+=" ${md##*/}: $m on ${d##*/} ($(disk_desc "$d"))\n"; done <<<"$others" v=$(tui --title "Old RAID on other disks" --radiolist \ "Old arrays on the chosen disks also use disks you did NOT choose:\n${list}\ Those disks are never wiped or repartitioned.\n\n\ KEEP: they stay in the old array, degraded, with their data. The new system may assemble \ it again.\n\n\ ERASE: erase the RAID superblock on exactly these partitions. Their data can no longer be \ mounted: practically LOST. Nothing else on those disks changes." \ 24 78 2 \ keep "Keep their data (degraded old array)" "$(on 0 "$ZERO_OTHERS")" \ erase "Erase their RAID superblock (data LOST)" "$(on 1 "$ZERO_OTHERS")") || { back $?; return 0; } ZERO_OTHERS=0 if [[ $v == erase ]]; then ZERO_OTHERS=1; fi } step_level() { local d size opts=() v title text SMALLEST_BYTES=0 for d in "${DISKS[@]}"; do size=$(lsblk -dnbo SIZE "$(readlink -f "$d")") if ((SMALLEST_BYTES == 0 || size < SMALLEST_BYTES)); then SMALLEST_BYTES=$size; fi done # usable_bytes for 1 disk at RAID 1 is the disk itself, which is what vg_bytes needs. if single; then LEVEL=1 SKIP=1; return 0; fi mapfile -t opts < <(level_options ${#DISKS[@]} "$SMALLEST_BYTES") title="RAID level" text="RAID level for /, /home and swap (/boot is always RAID 1)." if ((ZFS)); then title="ZFS layout" text="Layout of pool rpool (bpool, for /boot, is always a mirror; swap gets \ md RAID at the matching level)." fi while :; do # --no-tags: the level number would only repeat the description, or contradict ZFS's name. v=$(tui --title "$title" --no-tags --radiolist "$text\nSizes assume the smallest chosen disk." \ 16 78 5 "${opts[@]}") || { back $?; return 0; } if grep -q "\[raid$v\]" /proc/mdstat; then break; fi msg --title "RAID level" --msgbox "This rescue system's kernel can't run RAID $v (its module didn't load). Choose another level." 8 78 || true done LEVEL=$v } # Why the chosen disks can't be wiped, or nothing. Arrays, LVM and dm-crypt the rescue merely # activated are fine (wipe_disk takes them apart); mounted ones may be in use, and whatever also # lives on a disk that wasn't chosen must not be touched (an md array only loses a member). disks_busy() { local d dev x for d in "${DISKS[@]}"; do x=$(lsblk -lnpo NAME,MOUNTPOINT "$d" | awk 'NF > 1 && !s {s = $1 " is in use (" $2 ")"} END {print s}') if [[ $x ]]; then echo "${d##*/}: $x. Unmount it (or swapoff) first." return fi x=$(zfs_imported "$d") if [[ $x ]]; then echo "${d##*/} is in ZFS pool $x, imported in the rescue. Export it first: zpool export $x" return fi for dev in $(lsblk -lnpo NAME "$d"); do x=$(unchosen_disk "$dev" md) if [[ $x ]]; then echo "$dev on ${d##*/} also uses $x, which you didn't choose. Choose it too, or take $dev apart yourself first." return fi done done } # unchosen_disk DEV [md]: a disk that DEV is built from (lsblk -s, down to whole disks) but that # wasn't chosen, or nothing. With md, not below md arrays: wipe_disk only stops one (no data # written) and wipes the chosen disk's members; the other disks keep their part, degraded. unchosen_disk() { local d x chosen=' ' for d in "${DISKS[@]}"; do chosen+="$(readlink -f "$d") "; done # The ASCII tree's indent is the depth: skip the lines deeper than an md array (its members). for x in $(lsblk -snipo NAME,TYPE "$1" | awk -v md="${2:-}" '{ d = index($0, "/dev/"); $0 = substr($0, d) if (cut && d > cut) next cut = 0 if (md && $2 ~ /^raid/) cut = d else if ($2 == "disk" || $2 == "loop") print $1 }'); do if [[ $chosen != *" $x "* ]]; then echo "$x" return fi done } # vg_elsewhere: a disk outside the chosen ones that holds part of a volume group named $VG, or # nothing. A $VG only on the chosen disks goes with the wipe. vg_elsewhere() { local pv x for pv in $(pvs --noheadings -o pv_name,vg_name 2>/dev/null | awk -v vg="$VG" '$2 == vg {print $1}'); do x=$(unchosen_disk "$pv") if [[ $x ]]; then echo "$x" return fi done } # zfs_imported DISK: an imported ZFS pool with a vdev on DISK, or nothing. It holds the disk open; # unlike md and LVM, reroot doesn't take pools apart. zfs_imported() { command -v zpool >/dev/null || return 0 local devs devs=" $(lsblk -lnpo NAME "$1" | tr '\n' ' ')" { zpool list -vHPL 2>/dev/null || true; } | awk -v devs="$devs" '/^[^\t]/ {p = $1} index(devs, " " $1 " ") && !s {s = p} END {print s}' } # zfs_elsewhere: "POOL on DISK" for a pool named rpool or bpool on a disk that wasn't chosen, or # nothing. Pools are imported by name at boot, so the old one would clash with the new one. zfs_elsewhere() { local dev x for dev in $(lsblk -lnpo NAME); do [[ $(probe TYPE "$dev") == zfs_member && $(probe LABEL "$dev") =~ ^[br]pool$ ]] || continue x=$(unchosen_disk "$dev") if [[ $x ]]; then echo "$(probe LABEL "$dev") on $x" return fi done } capture_network() { # ip -6 errors when the rescue has IPv6 disabled; awk reads all input so ip can't hit SIGPIPE. NET_DEV=$({ ip -4 route show default; ip -6 route show default 2>/dev/null || true; } | awk '!dev {for (i = 1; i < NF; i++) if ($i == "dev") dev = $(i + 1)} END {print dev}') [[ $NET_DEV ]] || die "rescue system has no default route; cannot carry over the network" NET_MAC=$(cat "/sys/class/net/$NET_DEV/address") local lines lines=$(ip -o addr show dev "$NET_DEV" scope global) mapfile -t NET_ADDRS < <(addrs_from_ip <<<"$lines") NET_PEER=$(peer_from_ip <<<"$lines") NET_RESCUE_ADDR=${NET_ADDRS[0]:-} # "dynamic" = leased by DHCP, so the network menu preselects DHCP for the new system too. NET_DYNAMIC=0 if [[ $(ip -o -4 addr show dev "$NET_DEV" scope global) == *dynamic* ]]; then NET_DYNAMIC=1; fi mapfile -t NET_ROUTES < <({ ip -4 route show dev "$NET_DEV" | sed 's|^default|0.0.0.0/0|' { ip -6 route show dev "$NET_DEV" 2>/dev/null || true; } | sed 's|^default|::/0|' } | awk '$2 == "via" && !seen[$1]++ {print $1, $3}') local conf for conf in /etc/resolv.conf /run/systemd/resolve/resolv.conf; do mapfile -t NET_DNS < <(awk '$1 == "nameserver" && $2 !~ /^127\./ {print $2}' "$conf" 2>/dev/null) ((${#NET_DNS[@]})) && break done ((${#NET_ADDRS[@]})) || die "no global address on $NET_DEV" ((${#NET_ROUTES[@]})) || die "no gateway route on $NET_DEV" ((${#NET_DNS[@]})) || die "no DNS server found in the rescue system" } # CIDRs from `ip -o addr` lines. A point-to-point line ("inet A peer P/32") has no prefix on A. addrs_from_ip() { awk '!/temporary/ {if ($5 == "peer") print $4 ($3 == "inet6" ? "/128" : "/32"); else print $4}'; } peer_from_ip() { awk '$3 == "inet" && $5 == "peer" && !p {p = $6; sub("/.*", "", p)} END {print p}'; } # Proxmox: the NIC gets a fixed name by its MAC, so the config below can't miss it when the # installed system names it differently from the rescue. Type=ether: not the bridge, which # carries the same MAC. render_nic_link() { printf '[Match]\nMACAddress=%s\nType=ether\n\n[Link]\nName=nic0\n' "$NET_MAC" } # Proxmox: /etc/network/interfaces (ifupdown2), with the NIC in bridge vmbr0 like Proxmox's own # installer sets it up. The bridge keeps the NIC's MAC: hosters filter by it. render_interfaces() { local a r v4=() v6=() gw4='' gw6='' extra=() bridge printf -v bridge '\tbridge-ports nic0\n\tbridge-stp off\n\tbridge-fd 0\n\thwaddress %s\n' "$NET_MAC" printf 'auto lo\niface lo inet loopback\n\niface nic0 inet manual\n\nauto vmbr0\n' if ((NET_DHCP)); then printf 'iface vmbr0 inet dhcp\n%s' "$bridge" return fi for a in "${NET_ADDRS[@]}"; do if [[ $a == *:* ]]; then v6+=("$a"); else v4+=("$a"); fi done for r in "${NET_ROUTES[@]}"; do case ${r% *} in 0.0.0.0/0) gw4=${r#* } ;; ::/0) gw6=${r#* } ;; *) extra+=("$r") ;; esac done # A /32 without a point-to-point peer has its gateway outside the prefix: add it onlink. if [[ $gw4 && -z $NET_PEER && ${v4[0]:-} == */32 ]]; then extra=("0.0.0.0/0 $gw4" "${extra[@]}") gw4='' fi if ((${#v4[@]})); then printf 'iface vmbr0 inet static\n' printf '\taddress %s\n' "${v4[@]}" if [[ $NET_PEER ]]; then printf '\tpointopoint %s\n' "$NET_PEER"; fi if [[ $gw4 ]]; then printf '\tgateway %s\n' "$gw4"; fi printf '%s' "$bridge" bridge='' fi if ((${#v6[@]})); then printf 'iface vmbr0 inet6 static\n' printf '\taddress %s\n' "${v6[@]}" if [[ $gw6 ]]; then printf '\tgateway %s\n' "$gw6"; fi printf '%s' "$bridge" fi for r in "${extra[@]}"; do printf '\tpost-up ip route add %s via %s dev vmbr0 onlink\n' "${r% *}" "${r#* }" done } # The server's address for /etc/hosts: its first IPv4 address, else its first address. host_ip() { local a for a in "${NET_ADDRS[@]}"; do if [[ $a != *:* ]]; then echo "${a%/*}" return fi done echo "${NET_ADDRS[0]%/*}" } # systemd-networkd config for the new system, matched by MAC because interface names differ. render_network() { local a r peer_addr= printf '[Match]\nMACAddress=%s\n\n[Network]\n' "$NET_MAC" if ((NET_DHCP)); then printf 'DHCP=yes\n'; return; fi for a in "${NET_ADDRS[@]}"; do # The point-to-point peer belongs to the first IPv4 address, in its own [Address] section. if [[ $NET_PEER && -z $peer_addr && $a != *:* ]]; then peer_addr=$a continue fi printf 'Address=%s\n' "$a" done for a in "${NET_DNS[@]}"; do printf 'DNS=%s\n' "$a"; done if [[ $peer_addr ]]; then printf '\n[Address]\nAddress=%s\nPeer=%s/32\n' "$peer_addr" "$NET_PEER"; fi # GatewayOnLink: /32 setups have a gateway outside the address prefix. for r in "${NET_ROUTES[@]}"; do printf '\n[Route]\nDestination=%s\nGateway=%s\nGatewayOnLink=yes\n' "${r% *}" "${r#* }" done } load_ssh_keys() { local k AUTH_KEYS= if ((${#SSH_KEYS[@]} == 0)) && [[ -s /root/.ssh/authorized_keys ]]; then SSH_KEYS=(/root/.ssh/authorized_keys); fi if ((${#SSH_KEYS[@]})); then AUTH_KEYS=$(for k in "${SSH_KEYS[@]}"; do if [[ -f $k ]]; then cat "$k"; else printf '%s\n' "$k"; fi done | grep -Ev '^[[:space:]]*(#|$)') || die "no SSH key found in: ${SSH_KEYS[*]}" fi } # Keys-only SSH without any key would lock everyone out. login_possible() { ((!SSH || SSH_PASSWORD)) || [[ $AUTH_KEYS ]]; } key_count() { if [[ $AUTH_KEYS ]]; then grep -c . <<<"$AUTH_KEYS"; else echo 0; fi; } on() { if [[ $1 == "$2" ]]; then echo ON; else echo OFF; fi; } # radiolist state # ask VAR TITLE TEXT VALIDATOR: input box, repeated until VALIDATOR accepts the value. Back sets BACK. ask() { local v=${!1} while :; do v=$(tui --title "$2" --inputbox "$3" 10 78 "$v") || { back $?; return 0; } if "$4" "$v"; then printf -v "$1" '%s' "$v" return fi msg --title "$2" --msgbox "Not valid: \"$v\"" 8 60 || true done } # pick VAR TITLE TEXT VALIDATOR TAG DESC...: list menu preselecting $VAR; "other" asks for free input. pick() { local var=$1 title=$2 text=$3 valid=$4 cur=${!1} items=() found=0 v shift 4 while (($#)); do items+=("$1" "$2" "$(on "$cur" "$1")") if [[ $1 == "$cur" ]]; then found=1; fi shift 2 done if ((!found)); then items=("$cur" "(from the rescue system)" ON "${items[@]}"); fi items+=(other "Other: type it in" OFF) while :; do v=$(tui --title "$title" --radiolist "$text" 20 78 12 "${items[@]}") || { back $?; return 0; } if [[ $v != other ]]; then printf -v "$var" '%s' "$v" return 0 fi ask "$var" "$title" "$text" "$valid" if ((!BACK)); then return 0; fi BACK=0 # back from the input box: show the list again done } # Static network typed in by hand; every field starts with what "copy from the rescue" would use. # Back from any field returns to the network menu. ask_network_custom() { local t="Custom network" a a4='' g4='' a6='' g6='' r dns="${NET_DNS[*]}" for a in "${NET_ADDRS[@]}"; do if [[ $a == *:* ]]; then a6=${a6:-$a}; else a4=${a4:-$a}; fi done for r in "${NET_ROUTES[@]}"; do case ${r% *} in 0.0.0.0/0) g4=${r#* } ;; ::/0) g6=${r#* } ;; esac done while :; do ask a4 "$t" "IPv4 address with prefix, e.g. 203.0.113.5/24 (empty = no IPv4):" valid_cidr4_opt if ((BACK)); then return 0; fi if [[ $a4 ]]; then ask g4 "$t" "IPv4 gateway (empty = the point-to-point peer):" valid_ip4_opt if ((BACK)); then return 0; fi ask NET_PEER "$t" "Point-to-point peer, only if your hoster requires one (empty = none):" valid_ip4_opt if ((BACK)); then return 0; fi else g4='' NET_PEER='' fi ask a6 "$t" "IPv6 address with prefix, e.g. 2001:db8::2/64 (empty = no IPv6):" valid_cidr6_opt if ((BACK)); then return 0; fi if [[ $a6 ]]; then ask g6 "$t" "IPv6 gateway (often fe80::1):" valid_ip6_opt if ((BACK)); then return 0; fi else g6= fi ask dns "$t" "DNS servers, separated by spaces:" valid_dns if ((BACK)); then return 0; fi if [[ $a4 && -z $g4 ]]; then g4=$NET_PEER; fi if [[ $a4 || $a6 ]] && [[ -z $a4 || $g4 ]] && [[ -z $a6 || $g6 ]]; then break; fi msg --title "$t" --msgbox "Enter at least one address, and a gateway (or point-to-point peer) for each." 8 78 || true done NET_ADDRS=() NET_ROUTES=() if [[ $a4 ]]; then NET_ADDRS+=("$a4") && NET_ROUTES+=("0.0.0.0/0 $g4"); fi if [[ $a6 ]]; then NET_ADDRS+=("$a6") && NET_ROUTES+=("::/0 $g6"); fi read -ra NET_DNS <<<"$dns" } # Every screen in order; each step_NAME shows one, preselected with the current answer. # A step sets BACK to return to the previous screen, SKIP when it doesn't apply (passed in the # direction of travel), or JUMP to continue at a named step. Steps never return non-zero: a # function called as a condition runs without set -e. ask_settings() { local steps=(disks md_others os storage level hostname keymap locale layout swap_size pool_size root_size home_size data_size fit network network_custom user root ssh ssh_key root_pw user_pw confirm) local i=0 dir=1 j while ((i < ${#steps[@]})); do BACK=0 SKIP=0 JUMP='' "step_${steps[i]}" if [[ $JUMP ]]; then for j in "${!steps[@]}"; do if [[ ${steps[j]} == "$JUMP" ]]; then i=$j; fi done dir=1 continue fi if ((BACK)); then dir=-1; elif ((!SKIP)); then dir=1; fi i=$((i + dir)) if ((i < 0)); then i=0; fi # Back on the first screen done } # A menu, not a radiolist: the rows with a blank tag are group headers and shouldn't get a radio # button (a "-" tag would be read as an option). Distributions first, then platforms built on one. step_os() { local v while :; do v=$(tui --title "Operating system" --default-item "$OS" --menu "Install which system?" 16 78 8 \ " " "--- Distributions ---" \ debian-12 "Debian 12 (bookworm)" \ debian-13 "Debian 13 (trixie)" \ ubuntu-24.04 "Ubuntu 24.04 LTS (noble)" \ ubuntu-26.04 "Ubuntu 26.04 LTS (resolute)" \ " " "--- Platforms ---" \ proxmox-9 "Proxmox VE 9 (on Debian 13 trixie), experimental") || { back $?; return 0; } [[ $v == *[![:space:]]* ]] && break # else a header: ask again done OS=$v set_os } step_hostname() { ask HOSTNAME_NEW "Hostname" "Hostname of the new system:" valid_hostname; } step_keymap() { pick KEYMAP "Keyboard" "Keyboard layout of the new system (preselected: the rescue's):" valid_keymap \ us "English (US)" gb "English (UK)" de "German" ch "Swiss" fr "French" be "Belgian" \ nl "Dutch" es "Spanish" it "Italian" pt "Portuguese" br "Portuguese (Brazil)" pl "Polish" \ cz "Czech" se "Swedish" no "Norwegian" dk "Danish" "fi" "Finnish" ru "Russian" tr "Turkish" jp "Japanese" } step_locale() { pick LOCALE "Language" "Language and formats (locale) of the new system:" valid_locale \ en_US.UTF-8 "English (US)" en_GB.UTF-8 "English (UK)" de_DE.UTF-8 "German" \ de_AT.UTF-8 "German (Austria)" de_CH.UTF-8 "German (Switzerland)" fr_FR.UTF-8 "French" \ es_ES.UTF-8 "Spanish" it_IT.UTF-8 "Italian" nl_NL.UTF-8 "Dutch" pl_PL.UTF-8 "Polish" \ pt_BR.UTF-8 "Portuguese (Brazil)" C.UTF-8 "Minimal: no translations" } # Filesystems on md RAID (partitions on a single disk), LVM on it, or ZFS pools. Proxmox: LVM or # ZFS, like its own installer. ZFS needs ZFS in the rescue: zfs_ready sets it up after asking. step_storage() { local v=md on_raid="on md RAID" items=() vm="" if single; then on_raid="on the disk"; fi if ((ZFS)); then v=zfs; elif ((LVM || PVE)); then v=lvm; fi if ((PVE)); then vm=", VM disks in a thin pool (local-lvm)" else items+=(md "ext4 $on_raid: a partition per filesystem" "$(on "$v" md)") fi items+=(lvm "LVM $on_raid: volumes that can grow later$vm" "$(on "$v" lvm)") if ((PVE)); then vm=", VM disks as datasets (local-zfs)"; fi items+=(zfs "ZFS (EXPERIMENTAL): pools with snapshots and checksums$vm" "$(on "$v" zfs)") while :; do v=$(tui --title "Storage" --radiolist "How to store the system on the chosen disks:" 11 78 3 "${items[@]}") || { back $?; return 0; } if [[ $v != zfs ]] || zfs_ready; then break; fi done LVM=0 ZFS=0 case $v in lvm) LVM=1 ;; zfs) ZFS=1 ;; esac } step_layout() { local sel text="/boot (RAID 1) and / are always separate. Extras:" home=() local nozfs="Swap is never on ZFS (it can deadlock there): it gets md RAID." if ((ZFS)); then text="ZFS: /boot in pool bpool (GRUB reads it); / and a separate /home as datasets in pool \ rpool. $nozfs Extras:" fi if ((PVE)); then text="Proxmox VE: LVM with / and a thin pool for VM disks (local-lvm), like Proxmox's own \ installer.\n/boot (RAID 1) stays separate. Extras:" if ((ZFS)); then text="Proxmox VE on ZFS: / and VM disks (local-zfs) as datasets in pool rpool, /boot in \ pool bpool. $nozfs Extras:" fi else home=(home "Separate /home" "$( ((HOME_PART)) && echo ON || echo OFF)") fi sel=$(tui --title "Layout" --separate-output --checklist "$text" 12 78 2 "${home[@]}" \ swap "Swap" "$([[ $SWAP_SIZE ]] && echo ON || echo OFF)") || { back $?; return 0; } HOME_PART=0 if [[ $sel == *home* ]]; then HOME_PART=1; fi if [[ $sel == *swap* ]]; then SWAP_SIZE=${SWAP_SIZE:-8G}; else SWAP_SIZE=; fi } # Partitions are sized per disk (ZFS's swap too); LVM volumes in total (Proxmox: LVM unless ZFS). per_disk() { ((LVM || (PVE && !ZFS))) || echo " per disk"; } step_swap_size() { if [[ -z $SWAP_SIZE ]]; then SKIP=1; return 0; fi ask SWAP_SIZE "Swap" "Swap size$(per_disk) (e.g. 8G):" valid_size } # ZFS: rpool's partition is sized first; the datasets share the pool, so their sizes are limits # (quota), up to what the pool holds. step_pool_size() { if ((!ZFS)); then SKIP=1; return 0; fi ask ZFS_SIZE "rpool" "Size of the partition for pool rpool, per disk (e.g. 500G), empty = all \ remaining space:" valid_size_or_rest } # zfs_limit_text DIR: the question for a dataset's limit, with the pool's size. zfs_limit_text() { echo "Size limit of $1 (a ZFS quota: the datasets share rpool, which holds about \ $(numfmt --to=iec "$(rpool_bytes)")), e.g. 50G, empty = no limit:" } step_root_size() { if ((PVE && ZFS)); then SKIP=1 elif ((ZFS)); then ask ROOT_SIZE "Root" "$(zfs_limit_text /)" valid_zfs_limit elif ((PVE)); then ROOT_SIZE=${ROOT_SIZE:-$(pve_root_size)} ask ROOT_SIZE "Root" "Size of / (also holds ISOs, templates and backups). Proxmox's installer \ gives it a quarter of the space, at most 96G:" valid_size elif ((HOME_PART)); then ROOT_SIZE=${ROOT_SIZE:-50G} ask ROOT_SIZE "Root" "Size of /$(per_disk) (e.g. 50G):" valid_size else ask ROOT_SIZE "Root" "Size of /$(per_disk) (e.g. 50G), empty = all remaining space:" valid_size_or_rest fi } step_home_size() { if ((!HOME_PART)); then SKIP=1; return 0; fi if ((ZFS)); then ask HOME_SIZE "/home" "$(zfs_limit_text /home)" valid_zfs_limit return 0 fi ask HOME_SIZE "/home" "Size of /home$(per_disk) (e.g. 500G), empty = all remaining space:" valid_size_or_rest } # Proxmox's installer gives / a quarter of the space, at most 96G; the rest is for VMs. pve_root_size() { local g=$(($(vg_bytes) / 4 >> 30)) if ((g > 96)); then g=96; fi if ((g < 8)); then g=8; fi echo "${g}G" } step_data_size() { if ((!PVE || ZFS)); then SKIP=1; return 0; fi ask DATA_SIZE "VM storage" "Size of the thin pool for VM and container disks (Proxmox storage \ local-lvm), empty = all remaining space:" valid_size_or_rest } # No screen when the sizes fit; otherwise say why and go back to the layout. step_fit() { local need have text other='' where plan_partitions if ((ZFS)); then other=$(zfs_elsewhere); fi if [[ $other ]]; then msg --title "ZFS" --msgbox "There is already a ZFS pool $other, which you didn't choose. Pools \ are imported by name at boot, so it would clash with the new one. Rename or destroy it (zpool import -N \ OLD NEW, zpool destroy), or choose another storage." 10 78 || true JUMP=storage return 0 fi if ((LVM)); then other=$(vg_elsewhere) if [[ $other ]]; then msg --title "LVM" --msgbox "A volume group named $VG already exists on $other, which you didn't \ choose. Rename it (vgrename) or choose another storage." 9 78 || true JUMP=storage return 0 fi # 4 MiB per volume: LVM rounds sizes up to whole extents. need=$(($(sum_bytes "${VOLS[@]}") + ${#VOLS[@]} * (4 << 20))) have=$(vg_bytes) if ((have < 0)); then have=0; fi where="RAID $LEVEL on the chosen disks leaves" if single; then where="the chosen disk leaves"; fi text="These volumes need $(numfmt --to=iec "$need") (at least 1G for one that takes the rest), but \ $where about $(numfmt --to=iec "$have") for LVM." else need=$(layout_bytes) have=$SMALLEST_BYTES text="These partitions need $(numfmt --to=iec "$need") per disk (at least 1G for one that takes \ the rest), but the smallest chosen disk has $(numfmt --to=iec "$have")." fi if ((need <= have)); then SKIP=1; return 0; fi msg --title "Layout" --msgbox "$text\n\nMake swap, / or /home smaller." 10 78 || true JUMP=layout } step_network() { local v=static if ((NET_DHCP)); then v=dhcp; elif ((NET_CUSTOM)); then v=custom; fi v=$(tui --title "Network" --radiolist \ "Network for the new system (card $NET_DEV in the rescue, matched by MAC).\nThe rescue got its address $( ((NET_DYNAMIC)) && echo "by DHCP" || echo "statically")." 14 78 3 \ dhcp "DHCP" "$(on "$v" dhcp)" \ static "Static: copy $NET_RESCUE_ADDR and its routes and DNS" "$(on "$v" static)" \ custom "Custom: enter addresses, gateways, point-to-point peer, DNS" "$(on "$v" custom)") || { back $?; return 0; } NET_DHCP=0 NET_CUSTOM=0 case $v in dhcp) NET_DHCP=1 ;; static) capture_network ;; # undoes an earlier custom entry custom) NET_CUSTOM=1 ;; esac } step_network_custom() { if ((!NET_CUSTOM)); then SKIP=1; return 0; fi ask_network_custom } step_user() { ask USER_NEW "User" "Create a user with sudo rights (empty = none):" valid_user; } step_root() { local v=keep # Proxmox VE's web interface logs in as root (root@pam), and cluster joins use root over SSH. if [[ -z $USER_NEW ]] || ((PVE)); then DISABLE_ROOT=0 SKIP=1 return 0 fi if ((DISABLE_ROOT)); then v=lock; fi v=$(tui --title "Root" --radiolist "Root account ($USER_NEW gets sudo either way):" 10 78 2 \ keep "Keep root, with a password" "$(on "$v" keep)" \ lock "Disable root: password locked, no SSH login" "$(on "$v" lock)") || { back $?; return 0; } DISABLE_ROOT=0 if [[ $v == lock ]]; then DISABLE_ROOT=1; fi } step_ssh() { local v=password if ((!SSH)); then v=off; elif ((!SSH_PASSWORD)); then v=keys; fi v=$(tui --title "SSH" --radiolist "SSH login for the new system ($(key_count) key(s) found):" 12 78 3 \ password "Password or key" "$(on "$v" password)" \ keys "Keys only" "$(on "$v" keys)" \ off "No SSH server (console access only)" "$(on "$v" off)") || { back $?; return 0; } SSH=1 SSH_PASSWORD=0 case $v in password) SSH_PASSWORD=1 ;; off) SSH=0 ;; esac } step_ssh_key() { local k if ((!SSH)); then SKIP=1; return 0; fi k=$(tui --title "SSH key" --inputbox \ "Paste a public key to add (optional, $(key_count) found already):" 10 78) || { back $?; return 0; } if [[ $k =~ ^(ssh-|ecdsa-|sk-) ]]; then AUTH_KEYS+=${AUTH_KEYS:+$'\n'}$k elif [[ $k ]]; then msg --title "SSH key" --msgbox "That doesn't look like a public key (ssh-ed25519 AAAA...); not added." 8 78 || true fi if ! login_possible; then msg --title "SSH" --msgbox "Keys only needs at least one key." 8 50 || true BACK=1 fi } step_root_pw() { if ((DISABLE_ROOT)); then SKIP=1; return 0; fi ask_password root ROOT_PW } step_user_pw() { if [[ -z $USER_NEW ]]; then SKIP=1; return 0; fi ask_password "$USER_NEW" USER_PW } # ask_password ACCOUNT VAR: password box twice, store the password in VAR. ask_password() { local a b while :; do a=$(tui --title "Password" --passwordbox "Password for $1:" 9 78) || { back $?; return 0; } b=$(tui --title "Password" --passwordbox "Repeat the password for $1:" 9 78) || { back $?; BACK=0; continue; } if [[ $a && $a == "$b" ]]; then break; fi msg --title "Password" --msgbox "Empty or not matching, try again." 8 50 || true done printf -v "$2" '%s' "$a" } render_sshd() { local root=prohibit-password pw=no if ((SSH_PASSWORD)); then root=yes pw=yes; fi if ((DISABLE_ROOT)); then root=no; fi printf 'PermitRootLogin %s\nPasswordAuthentication %s\n' "$root" "$pw" } install_keys() { # HOME [OWNER] [[ $AUTH_KEYS ]] || return 0 install -d -m 700 "$TARGET$1/.ssh" printf '%s\n' "$AUTH_KEYS" >"$TARGET$1/.ssh/authorized_keys" chmod 600 "$TARGET$1/.ssh/authorized_keys" if [[ ${2:-} ]]; then in_target chown -R "$2:$2" "$1/.ssh"; fi } setup_accounts() { if ((DISABLE_ROOT)); then in_target passwd -l root >/dev/null else printf 'root:%s\n' "$ROOT_PW" | in_target chpasswd install_keys /root fi if [[ $USER_NEW ]]; then in_target useradd -m -s /bin/bash -G sudo "$USER_NEW" printf '%s:%s\n' "$USER_NEW" "$USER_PW" | in_target chpasswd install_keys "/home/$USER_NEW" "$USER_NEW" fi if ((SSH)); then # sshd uses the first value it reads and includes sshd_config.d first, so this file wins. render_sshd >"$TARGET/etc/ssh/sshd_config.d/10-reroot.conf" fi } step_confirm() { local d data active answer v others md m plan_partitions echo echo "Install $OS ($SUITE), $( ((UEFI)) && echo UEFI || echo BIOS) boot, hostname $HOSTNAME_NEW" echo "Keyboard $KEYMAP, locale $LOCALE" echo "Package downloads: $( ((CACHE_RAM)) && echo "RAM" || echo "disk (needs $CACHE_RAM_MIN_MB MB free RAM for RAM)"), $MEM_AVAIL_MB MB RAM available" if single; then echo "Single disk, no RAID: a failed disk loses the system" elif ((ZFS)); then echo "ZFS: pool rpool ($(zfs_kind "$LEVEL")) for /, pool bpool (mirror) for /boot$([[ $SWAP_SIZE ]] && echo ", swap on md RAID $LEVEL")" else echo "RAID $LEVEL for / $([[ $SWAP_SIZE ]] && echo "swap ")$( ((HOME_PART)) && echo "/home ")(/boot: RAID 1)" fi if ((ZFS)); then echo "ZFS datasets in rpool (about $(numfmt --to=iec "$(rpool_bytes)")): $ZFS_ROOT (/${ROOT_SIZE:+, at most $ROOT_SIZE})$( ((HOME_PART)) && echo ", rpool/home${HOME_SIZE:+ (at most $HOME_SIZE)}, rpool/home/root"), rpool/var/log, rpool/var/spool$( ((PVE)) && echo ", rpool/data (VM disks, Proxmox storage local-zfs)")" fi echo "Partitions per disk: ${PARTS[*]} (0 = rest of disk)" if [[ ${PARTS[-1]#*:} != 0 ]]; then echo "The space after the last partition stays unpartitioned."; fi if ((LVM)); then echo "LVM volumes in $VG: ${VOLS[*]} (0 = rest)" if ((PVE)); then echo "data is a thin pool for VM and container disks (Proxmox storage local-lvm)."; fi if [[ ${VOLS[-1]#*:} != 0 ]]; then echo "The rest stays free in $VG, to grow the volumes later."; fi fi echo echo "ALL DATA ON THESE DISKS WILL BE ERASED:" for d in "${DISKS[@]}"; do printf ' %s %s\n' "$d" "$(disk_desc "$d")" data=$(disk_data "$d") if [[ $data ]]; then printf ' \033[1;33mWARNING: this disk contains data:\033[0m\n' printf ' %s\n' "${data//$'\n'/$'\n '}" fi active=$(lsblk -lnpo NAME,TYPE "$d" | awk '$2 ~ /^(raid|lvm|crypt|dm)/ && !seen[$1]++ {printf " %s", $1}') if [[ $active ]]; then printf ' active in the rescue, stopped before wiping:%s\n' "$active"; fi done others=$(md_others) if [[ $others ]] && ((ZERO_OTHERS)); then printf '\033[1;31mALSO ERASED on disks you did NOT choose: the RAID superblock of these partitions\033[0m\n' printf '\033[1;31m(nothing else on those disks; their data can no longer be mounted):\033[0m\n' elif [[ $others ]]; then echo "Kept on disks you didn't choose (stay in the old array, degraded, with their data):" fi while read -r md m d; do if [[ $m ]]; then printf ' %s on %s (was in %s)\n' "$m" "$d" "${md##*/}"; fi done <<<"$others" echo if ((NET_DHCP)); then echo "Network: DHCP on the card that is $NET_DEV in the rescue:" elif ((NET_CUSTOM)); then echo "Network: custom, on the card that is $NET_DEV in the rescue:" else echo "Network carried over from $NET_DEV:" fi if ((PVE)); then render_interfaces; else render_network; fi | sed 's/^/ /' echo echo "Root: $( ((DISABLE_ROOT)) && echo "locked, no SSH login" || echo "password set")" if [[ $USER_NEW ]]; then echo "User: $USER_NEW (sudo, password set)"; fi if ((SSH)); then echo "SSH: on, $(key_count) key(s), sshd config:" render_sshd | sed 's/^/ /' else echo "SSH: off (console access only)" fi echo printf 'Type "wipe" to install, "back" to change settings: ' read -r answer /dev/null || true # ZFS keeps two of its four labels at the end of a device, where wipefs doesn't look. if command -v zpool >/dev/null; then zpool labelclear -f "$p" 2>/dev/null || true; fi wipefs -aq "$p" done sgdisk --zap-all "$disk" >/dev/null } partition_disk() { local i n name size type args=() for i in "${!PARTS[@]}"; do n=$((i + 1)) name=${PARTS[i]%%:*} size=${PARTS[i]#*:} case $name in bios) type=EF02 ;; esp) type=EF00 ;; zfs) type=BF00 ;; *) type=FD00 ;; esac if [[ $name == boot ]] && ((ZFS)); then type=BF01; fi # bpool [[ $size == 0 ]] || size=+$size args+=(-n "$n:0:$size" -t "$n:$type" -c "$n:$name") done sgdisk "${args[@]}" "$1" >/dev/null } wait_for() { local i for i in {1..50}; do [[ -e $1 ]] && return sleep 0.2 done die "timed out waiting for $1" } # One LVM volume per filesystem on the lvm array, in VOLS order. A size 0 (only ever the last one) # takes the rest; otherwise the rest stays free in the volume group, to grow the volumes later. create_volumes() { local v size log "creating LVM volume group $VG" pvcreate -qy "$(vol lvm)" /dev/null >"/sys/block/$(basename "$(readlink -f "/dev/md/$1")")/md/sync_action" || true } setup_storage() { local d a v others=() plan_partitions if ((ZERO_OTHERS)); then mapfile -t others < <(md_others | awk '{print $2}'); fi # before the stop for d in "${DISKS[@]}"; do log "wiping $d" wipe_disk "$d" partition_disk "$d" done for a in "${others[@]}"; do log "erasing the old RAID superblock on $a (a disk you didn't choose)" mdadm --zero-superblock "$a" done udevadm settle for d in "${DISKS[@]}"; do wait_for "$(part "$d" "${PARTS[-1]%%:*}")"; done ARRAYS=(boot root) if [[ $SWAP_SIZE ]]; then ARRAYS+=(swap); fi if ((HOME_PART)); then ARRAYS+=(home); fi if ((LVM)); then ARRAYS=(boot lvm); fi if ((ZFS)); then ARRAYS=() if [[ $SWAP_SIZE ]]; then ARRAYS=(swap); fi fi if single; then # Like create_array: an old label at the same offset would come back (pvcreate refuses). for a in "${ARRAYS[@]}"; do wipefs -aq "$(vol "$a")"; done ARRAYS=() fi for a in "${ARRAYS[@]}"; do log "creating /dev/md/$a" if [[ $a == boot ]]; then create_array boot 1; else create_array "$a" "$LEVEL"; fi done if ((LVM)); then create_volumes; fi local fs=(boot "${VOLS[@]%%:*}") if ((ZFS)); then fs=("${VOLS[@]%%:*}"); fi # swap, if any; the rest is in the pools for v in "${fs[@]}"; do case $v in swap) mkswap -L swap "$(vol swap)" >/dev/null ;; data) ;; # Proxmox's thin pool: VM disks, no filesystem *) mkfs.ext4 -qF -L "$v" "$(vol "$v")" ;; esac done if ((UEFI)); then for d in "${DISKS[@]}"; do mkfs.vfat -F 32 -n EFI "$(part "$d" esp)" >/dev/null; done fi mkdir -p "$TARGET" if ((ZFS)); then create_pools # mounted below $TARGET else # noinit_itable: ext4 would zero its inode tables in the background now (GBs on a large # disk); the installed system does that instead. mount -o noinit_itable "$(vol root)" "$TARGET" mkdir -p "$TARGET/boot" mount -o noinit_itable "$(vol boot)" "$TARGET/boot" if ((HOME_PART)); then mkdir -p "$TARGET/home" && mount -o noinit_itable "$(vol home)" "$TARGET/home"; fi fi if ((UEFI)); then mkdir -p "$TARGET/boot/efi" && mount "$(part "${DISKS[0]}" esp)" "$TARGET/boot/efi"; fi } # Root on ZFS like the OpenZFS guides: bpool for /boot, restricted to the features GRUB reads, # across all disks like md's /boot; rpool at the chosen level for the rest. Both mounted below # $TARGET (altroot); exported at the end, so the new system imports them without -f. create_pools() { local d boot=() root=() compat=() quota=() for d in "${DISKS[@]}"; do boot+=("$(part "$d" boot)") root+=("$(part "$d" zfs)") done mapfile -t boot < <(vdev 1 "${boot[@]}") mapfile -t root < <(vdev "$LEVEL" "${root[@]}") # A rescue older than the target doesn't know its release's name, and has no newer features anyway. if [[ -f /usr/share/zfs/compatibility.d/$ZFS_COMPAT ]]; then compat=(-o "compatibility=$ZFS_COMPAT"); fi log "creating ZFS pools bpool and rpool" # The cache file lists bpool, which the new system imports with it (zfs-import-bpool.service). mkdir -p "$WORK" zpool create -f -o ashift=12 -o autotrim=on -o compatibility=grub2 -o "cachefile=$WORK/zpool.cache" \ -O devices=off -O acltype=posixacl -O xattr=sa -O compression=lz4 -O normalization=formD \ -O relatime=on -O canmount=off -O mountpoint=/boot -R "$TARGET" bpool "${boot[@]}" zpool create -f -o ashift=12 -o autotrim=on "${compat[@]}" \ -O acltype=posixacl -O xattr=sa -O dnodesize=auto -O compression=lz4 -O normalization=formD \ -O relatime=on -O canmount=off -O mountpoint=/ -R "$TARGET" rpool "${root[@]}" zfs create -o canmount=off -o mountpoint=none rpool/ROOT zfs create -o canmount=off -o mountpoint=none bpool/BOOT # Sizes are limits: the datasets share the pool (/var/log and /var/spool count apart from /). if [[ $ROOT_SIZE ]]; then quota=(-o "quota=$ROOT_SIZE"); fi zfs create -o canmount=noauto -o mountpoint=/ "${quota[@]}" "$ZFS_ROOT" zfs mount "$ZFS_ROOT" zfs create -o mountpoint=/boot "bpool/BOOT/${ZFS_ROOT##*/}" if ((HOME_PART)); then quota=() if [[ $HOME_SIZE ]]; then quota=(-o "quota=$HOME_SIZE"); fi zfs create "${quota[@]}" rpool/home zfs create -o mountpoint=/root rpool/home/root chmod 700 "$TARGET/root" fi zfs create -o canmount=off rpool/var zfs create -o canmount=off rpool/var/lib zfs create rpool/var/log zfs create rpool/var/spool if ((PVE)); then zfs create rpool/data; fi # VM disks (zvols), registered as local-zfs at first boot mkdir -p "$TARGET/etc/zfs" cp "$WORK/zpool.cache" "$TARGET/etc/zfs/" } # Download the newest *_all.deb of a Debian package and unpack it into $WORK/root. fetch_deb() { local pkg=$1 dir file dir=$DEB_POOL/${pkg:0:1}/$pkg file=$(curl -fsSL "$dir/" | grep -o "${pkg}_[^\"/]*_all\.deb" | grep -v '~' | sort -uV | tail -n1) [[ $file ]] || die "could not find $pkg in the Debian archive" mkdir -p "$WORK/$pkg" "$WORK/root" curl -fsSL -o "$WORK/$pkg/$file" "$dir/$file" (cd "$WORK/$pkg" && ar x "$file" && tar -xf data.tar.* -C "$WORK/root") } in_target() { chroot "$TARGET" /usr/bin/env DEBIAN_FRONTEND=noninteractive LC_ALL=C.UTF-8 \ PATH=/usr/sbin:/usr/bin:/sbin:/bin "$@" } write_resolv() { rm -f "$TARGET/etc/resolv.conf" printf 'nameserver %s\n' "${NET_DNS[@]}" >"$TARGET/etc/resolv.conf" } # Package downloads (debootstrap's and apt's) go to RAM when there's room: fewer writes to the # new disks while the RAID syncs, and nothing left behind. Unmounted with $TARGET at the end. cache_in_ram() { if ((CACHE_RAM)); then mkdir -p "$TARGET/var/cache/apt/archives/partial" # on disk, for apt after the tmpfs is gone mount -t tmpfs -o "size=${CACHE_RAM_SIZE},mode=755" reroot-cache "$TARGET/var/cache/apt/archives" fi } # Decided up front so the confirmation screen can show it. check_ram() { MEM_AVAIL_MB=$(awk '/^MemAvailable:/ {print int($2 / 1024)}' /proc/meminfo) CACHE_RAM=0 if ((MEM_AVAIL_MB >= CACHE_RAM_MIN_MB)); then CACHE_RAM=1; fi } bootstrap() { local keyring script rm -rf "$WORK" log "fetching debootstrap and $DISTRO keyring from the Debian archive" fetch_deb debootstrap if [[ $DISTRO == debian ]]; then fetch_deb debian-archive-keyring script=sid else fetch_deb ubuntu-keyring script=gutsy fi for keyring in "$WORK"/root/usr/share/keyrings/"$DISTRO"-archive-keyring.{pgp,gpg} ""; do [[ -f $keyring ]] && break done [[ $keyring ]] || die "$DISTRO archive keyring not found in the downloaded package" cache_in_ram # dpkg fsyncs every file it unpacks: thousands of disk flushes, slow on HDDs. A crash mid-install # means reinstalling anyway, and main syncs before unmounting. Removed at the end of configure. mkdir -p "$TARGET/etc/dpkg/dpkg.cfg.d" echo force-unsafe-io >"$TARGET/etc/dpkg/dpkg.cfg.d/reroot-unsafe-io" log "debootstrap $SUITE" # Generic sid/gutsy scripts work for any release, so a codename newer than this debootstrap is fine. DEBOOTSTRAP_DIR=$WORK/root/usr/share/debootstrap "$WORK/root/usr/sbin/debootstrap" \ --arch=amd64 --keyring="$keyring" "$SUITE" "$TARGET" "$MIRROR" \ "$WORK/root/usr/share/debootstrap/scripts/$script" "$TARGET/etc/apt/sources.list.d/pve-install-repo.sources" <<-EOF Types: deb URIs: http://download.proxmox.com/debian/pve Suites: $SUITE Components: pve-no-subscription Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg EOF printf 'postfix postfix/main_mailer_type select Local only\npostfix postfix/mailname string %s\n' \ "$HOSTNAME_NEW" | in_target debconf-set-selections } # proxmox-ve adds the enterprise repository, which needs a subscription: apt-get update (also the # web UI's daily one) fails on it with 401. Disabled, not removed: with a subscription it can be # switched back on in the web UI. The no-subscription repository from add_pve_repo stays. disable_pve_enterprise() { local f for f in "$TARGET"/etc/apt/sources.list.d/*.sources; do if grep -qs 'enterprise\.proxmox\.com' "$f" && ! grep -qs '^Enabled:' "$f"; then echo 'Enabled: no' >>"$f" fi done } detect_firmware() { local k=("$TARGET"/lib/modules/*) idx fallback if [[ $DISTRO == debian ]]; then idx=("$MIRROR/dists/$SUITE/non-free-firmware/Contents-"{all,amd64}.gz) fallback=(firmware-misc-nonfree firmware-intel-misc firmware-realtek firmware-bnx2 firmware-bnx2x firmware-qlogic) else # Whole-suite indexes (50-80 MB), so only the firmware lines are kept. idx=("$MIRROR/dists/"{"$SUITE","$SUITE-updates"}/Contents-amd64.gz) fallback=(linux-firmware) fi if ((PVE)); then : # pve-firmware, which the Proxmox kernel depends on, has all of it and conflicts with Debian's elif curl -fsSL "${idx[@]}" | gzip -dc | grep 'lib/firmware/' >"$WORK/contents"; then cat /sys/bus/*/devices/*/modalias 2>/dev/null | sort -u >"$WORK/modalias" || true # modprobe -R resolves a device's modalias to its driver module without loading anything. # shellcheck disable=SC2016 # expanded by sh in the target in_target sh -c 'while read -r a; do modprobe -S "$1" -R "$a"; done 2>/dev/null | sort -u | xargs -r modinfo -k "$1" -F firmware 2>/dev/null' sh "${k[0]##*/}" \ <"$WORK/modalias" >"$WORK/firmware" || true firmware_pkgs "$WORK/firmware" "$WORK/contents" else warn "could not fetch the firmware index; installing ${fallback[*]} instead" printf '%s\n' "${fallback[@]}" fi if [[ $DISTRO == debian ]]; then case $(awk -F': ' '/^vendor_id/ { v = $2 } END { print v }' /proc/cpuinfo) in GenuineIntel) echo intel-microcode ;; AuthenticAMD) echo amd64-microcode ;; esac fi } configure() { local m pkgs grub_devs comp="main non-free-firmware" store=local-lvm local add="pvesm add lvmthin local-lvm --vgname $VG --thinpool data --content images,rootdir" if ((ZFS)); then comp="main contrib non-free-firmware" # Debian's ZFS is in contrib store=local-zfs add="pvesm add zfspool local-zfs --pool rpool/data --sparse 1 --content images,rootdir" fi mount -t proc proc "$TARGET/proc" for m in dev dev/pts sys; do mount --bind "/$m" "$TARGET/$m"; done printf '#!/bin/sh\nexit 101\n' >"$TARGET/usr/sbin/policy-rc.d" chmod +x "$TARGET/usr/sbin/policy-rc.d" if [[ $DISTRO == debian ]]; then cat >"$TARGET/etc/apt/sources.list" <<-EOF deb $MIRROR $SUITE $comp deb $MIRROR $SUITE-updates $comp deb http://security.debian.org/debian-security $SUITE-security $comp EOF pkgs=(linux-image-amd64 apparmor) # apparmor came via Recommends; kept as Debian's security default if ((PVE)); then add_pve_repo # The Proxmox kernel (pulled in by proxmox-ve) instead of Debian's; chrony and postfix (local # only) as the Proxmox wiki recommends. pkgs=(proxmox-ve postfix open-iscsi chrony apparmor) fi else cat >"$TARGET/etc/apt/sources.list" <<-EOF deb $MIRROR $SUITE main restricted universe deb $MIRROR $SUITE-updates main restricted universe deb http://security.ubuntu.com/ubuntu $SUITE-security main restricted universe EOF pkgs=(linux-image-generic initramfs-tools) # only a Recommends of Ubuntu's kernel; no initrd = no boot from RAID # Provides linux-firmware, which the kernel depends on, without pulling every vendor's firmware # (~600 MB): detect_firmware adds what this machine needs. pkgs+=(linux-firmware-minimal) fi write_resolv in_target apt-get update -q "$TARGET/etc/default/keyboard" pkgs+=(console-setup locales) if ((SSH)); then pkgs+=(openssh-server); fi if [[ $USER_NEW ]]; then pkgs+=(sudo); fi if ((PVE)); then # Proxmox brings ifupdown2, whose DHCP client is dhclient. if ((NET_DHCP)); then pkgs+=(isc-dhcp-client); fi else # Split out of the systemd package on newer releases; install only where they exist. for m in systemd-networkd $( ((NET_DHCP)) && echo systemd-resolved); do if in_target apt-cache show "$m" >/dev/null 2>&1; then pkgs+=("$m"); fi done fi if ((UEFI)); then pkgs+=(grub-efi-amd64 efibootmgr) printf 'grub-efi-amd64 grub2/update_nvram boolean false\n' | in_target debconf-set-selections else pkgs+=(grub-pc) printf -v grub_devs '%s, ' "${DISKS[@]}" printf 'grub-pc grub-pc/install_devices multiselect %s\n' "${grub_devs%, }" | in_target debconf-set-selections fi log "installing ${pkgs[*]}" # Minimal server: Recommends would add X11 bits (xauth), thermald, sound firmware and the like. in_target apt-get install -y -q --no-install-recommends "${pkgs[@]}" >"$TARGET/etc/locale.gen" in_target locale-gen fi in_target update-locale "LANG=$LOCALE" in_target setupcon --save-only # cached console keymap, used early in boot and by the initramfs echo "$HOSTNAME_NEW" >"$TARGET/etc/hostname" # Proxmox needs the hostname to resolve to the server's address, not to 127.0.1.1. printf '127.0.0.1\tlocalhost\n%s\t%s\n::1\tlocalhost ip6-localhost ip6-loopback\n' \ "$( ((PVE)) && host_ip || echo 127.0.1.1)" "$HOSTNAME_NEW" >"$TARGET/etc/hosts" write_fstab mkdir -p "$TARGET/etc/systemd/network" if ((PVE)); then render_nic_link >"$TARGET/etc/systemd/network/10-reroot-nic0.link" render_interfaces >"$TARGET/etc/network/interfaces" # ifupdown2's postinst leaves Proxmox's default (only lo) as interfaces.new, which # pvenetcommit.service moves over this file at boot: no network. rm -f "$TARGET/etc/network/interfaces.new" write_resolv # Proxmox keeps its storage config in its cluster filesystem, which only runs on the booted # system: register the VM disk storage there once, then the unit removes itself. cat >"$TARGET/etc/systemd/system/reroot-storage.service" <<-EOF [Unit] Description=Register VM disk storage $store with Proxmox (once, set up by reroot) Requires=pve-cluster.service After=pve-cluster.service # pve-cluster counts as started before its filesystem is online ("pve cluster filesystem # not online"): retry for up to 10 minutes. StartLimitIntervalSec=600 StartLimitBurst=60 [Service] Type=oneshot Restart=on-failure RestartSec=5 ExecStart=/bin/sh -c 'pvesm status --storage $store >/dev/null 2>&1 || $add' ExecStart=/usr/sbin/pvesm set local --content iso,vztmpl,backup ExecStart=/bin/rm -f /etc/systemd/system/multi-user.target.wants/reroot-storage.service /etc/systemd/system/reroot-storage.service [Install] WantedBy=multi-user.target EOF in_target systemctl enable reroot-storage.service else render_network >"$TARGET/etc/systemd/network/10-reroot.network" in_target systemctl enable systemd-networkd fi if ((PVE)); then : # DHCP: dhclient writes resolv.conf elif ((NET_DHCP)); then # DNS servers come from DHCP; only systemd-resolved applies them. ln -sf /run/systemd/resolve/stub-resolv.conf "$TARGET/etc/resolv.conf" in_target systemctl enable systemd-resolved else write_resolv fi setup_accounts if ((ZFS)); then configure_zfs; fi if ((${#ARRAYS[@]})); then render_mdadm_conf >"$TARGET/etc/mdadm/mdadm.conf"; fi in_target update-initramfs -u -k all rm -f "$TARGET/usr/sbin/policy-rc.d" in_target apt-get clean # the downloaded .debs, when they went to disk rm -f "$TARGET/etc/dpkg/dpkg.cfg.d/reroot-unsafe-io" } # The OpenZFS guide's steps in the new system: root= for GRUB (it can't read rpool's features, so # its own guess would be wrong), bpool imported at boot, and zfs-list.cache, from which # zfs-mount-generator makes mount units (so /boot is mounted before /boot/efi). zed writes that # cache, but the target's zed may not talk to the rescue's module (another release): written here # like zed's cacher does, with the target's own property list, without the altroot. configure_zfs() { local p props cacher=("$TARGET"/usr/lib/*/zed.d/history_event-zfs-list-cacher.sh) sed -i "s|^GRUB_CMDLINE_LINUX=.*|GRUB_CMDLINE_LINUX=\"root=ZFS=$ZFS_ROOT\"|" "$TARGET/etc/default/grub" cat >"$TARGET/etc/systemd/system/zfs-import-bpool.service" <<-'EOF' [Unit] DefaultDependencies=no Before=zfs-import-scan.service Before=zfs-import-cache.service [Service] Type=oneshot RemainAfterExit=yes ExecStart=/sbin/zpool import -N -o cachefile=none bpool # Work-around to preserve zpool cache: ExecStartPre=-/bin/mv /etc/zfs/zpool.cache /etc/zfs/preboot_zpool.cache ExecStartPost=-/bin/mv /etc/zfs/preboot_zpool.cache /etc/zfs/zpool.cache [Install] WantedBy=zfs-import.target EOF in_target systemctl enable zfs-import-bpool.service props=$(zfs_list_props <"${cacher[0]}") [[ $props ]] || die "no property list in ${cacher[0]#"$TARGET"}" mkdir -p "$TARGET/etc/zfs/zfs-list.cache" for p in bpool rpool; do zfs list -H -t filesystem -o "$props" -r "$p" | strip_altroot | sort >"$TARGET/etc/zfs/zfs-list.cache/$p" done } # The PROPS="a,b\ ... " list from zed's zfs-list cacher script on stdin, continuation lines joined. zfs_list_props() { sed -n '/^PROPS="/,/"$/p' | tr -d '\\\n"' | sed 's/^PROPS=//'; } # zfs list lines (tab-separated, mountpoint second) as seen without the altroot $TARGET. strip_altroot() { awk -F '\t' -v OFS='\t' -v t="$TARGET" '$2 == t {$2 = "/"} index($2, t "/") == 1 {$2 = substr($2, length(t) + 1)} 1' } # Fixed md0 (/boot), md1 (/), ... like the Debian installer. Named ARRAY lines (/dev/md/boot) # make the new system assemble them as md127, md126, ... render_mdadm_conf() { local i m u printf 'HOMEHOST \nMAILADDR root\n' for i in "${!ARRAYS[@]}"; do m=${ARRAYS[i]} u=$(md_uuid "/dev/md/$m") printf 'ARRAY /dev/md%d metadata=1.2 UUID=%s name=%s:%s\n' "$i" "$u" "$HOSTNAME_NEW" "$m" done } md_uuid() { local u u=$(mdadm --detail --export "$1" | sed -n 's/^MD_UUID=//p') [[ $u ]] || die "no RAID UUID for $1" echo "$u" } uuid() { local u u=$(blkid -p -s UUID -o value "$1") [[ $u ]] || die "no UUID on $1" echo "$u" } write_fstab() { local fstab='' u if ((!ZFS)); then # ZFS mounts its datasets itself u=$(uuid "$(vol root)") fstab=$(printf 'UUID=%s\t/\text4\terrors=remount-ro\t0 1' "$u") u=$(uuid "$(vol boot)") fstab+=$(printf '\nUUID=%s\t/boot\text4\tdefaults\t0 2' "$u") fi if ((HOME_PART && !ZFS)); then u=$(uuid "$(vol home)") fstab+=$(printf '\nUUID=%s\t/home\text4\tdefaults\t0 2' "$u") fi if [[ $SWAP_SIZE ]]; then u=$(uuid "$(vol swap)") fstab+=$(printf '\nUUID=%s\tnone\tswap\tsw\t0 0' "$u") fi if ((UEFI)); then u=$(uuid "$(part "${DISKS[0]}" esp)") fstab+=$(printf '\nUUID=%s\t/boot/efi\tvfat\tumask=0077,nofail\t0 1' "$u") fi printf '%s\n' "${fstab#$'\n'}" >"$TARGET/etc/fstab" } install_bootloader() { local d i n if ((UEFI)); then log "installing GRUB (UEFI) on all ESPs" in_target grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=reroot --no-nvram in_target grub-install --target=x86_64-efi --efi-directory=/boot/efi --removable --no-nvram in_target update-grub # shortcut: GRUB package updates only refresh the first ESP; re-copy after major GRUB upgrades. mkdir -p "$WORK/esp" for d in "${DISKS[@]:1}"; do mount "$(part "$d" esp)" "$WORK/esp" cp -r "$TARGET/boot/efi/." "$WORK/esp/" umount "$WORK/esp" done for n in $(efibootmgr | sed -n 's/^Boot\([0-9A-Fa-f]\{4\}\)\*\{0,1\} reroot.*/\1/p'); do efibootmgr -q -b "$n" -B done # Created last-to-first so disk 1 ends up first in BootOrder. for ((i = ${#DISKS[@]} - 1; i >= 0; i--)); do efibootmgr -q -c -d "$(readlink -f "${DISKS[i]}")" -p "$(part_no esp)" \ -L "reroot disk $((i + 1))" -l '\EFI\reroot\grubx64.efi' done else log "installing GRUB (BIOS) on all disks" for d in "${DISKS[@]}"; do in_target grub-install --target=i386-pc "$d"; done in_target update-grub fi } main() { trap 'die "failed at line $LINENO: $BASH_COMMAND"' ERR parse_args "$@" preflight check_ram capture_network if ((NET_DYNAMIC)); then NET_DHCP=1; fi # rescue got DHCP: preselect it load_ssh_keys detect_locale_keymap ask_settings setup_storage bootstrap configure install_bootloader for a in "${ARRAYS[@]}"; do md_sync "$a" idle; done sync umount -R "$TARGET" # The pools carry the rescue's hostid while imported: exported, the new system imports them. if ((ZFS)); then zpool export bpool rpool; fi if single; then log "done. Reboot into the new system." else log "done. Reboot into the new system; RAID resync progress: cat /proc/mdstat" fi } # Run only when executed (also via curl | bash), not when sourced by the tests. if [[ ${BASH_SOURCE[0]:-$0} == "$0" ]]; then main "$@"; fi