diff --git a/installer/doc/FINDINGS.md b/docs/FINDINGS.md similarity index 100% rename from installer/doc/FINDINGS.md rename to docs/FINDINGS.md diff --git a/installer/doc/VM-BOOT-VERIFICATION.md b/docs/VM-BOOT-VERIFICATION.md similarity index 97% rename from installer/doc/VM-BOOT-VERIFICATION.md rename to docs/VM-BOOT-VERIFICATION.md index a148f11..5096743 100644 --- a/installer/doc/VM-BOOT-VERIFICATION.md +++ b/docs/VM-BOOT-VERIFICATION.md @@ -21,8 +21,9 @@ Phase 1 (install): 1. Boot the live ISO headless; get a root shell on the serial console. 2. Download the installer and test config from the host. -3. Write secrets to `0600` files and run: - `installer/bin/ai-installer --config test.conf --install --yes +3. Write secrets to `0600` files and run the installer binary (the original + run used the Bash prototype; the harness now serves `phoebus-installer`): + `phoebus-installer --config test.conf --install --yes --luks-passphrase-file FILE --user-password-file FILE` 4. Stages executed in order: `preflight, storage, stage3, fstab, portage, base packages, kernel, bootloader, users, services, desktop, @@ -206,7 +207,7 @@ Boot with the ISO detached (`serial-driver.py boot`): `/efi`; `vda2` is `crypto_LUKS`. This satisfies the Phase 2 exit gate of `docs/BASH-MIGRATION.md`: the only -proven boot path no longer depends on `installer/bin/ai-installer`. +proven boot path no longer depends on the retired Bash installer. ## Known remaining work diff --git a/installer/README.md b/installer/README.md deleted file mode 100644 index 448a151..0000000 --- a/installer/README.md +++ /dev/null @@ -1,124 +0,0 @@ -# Phoebus OS installer - -A deterministic, text-mode installer for Phoebus OS, inspired by -`void-installer`. It is usable entirely without an LLM; AI only augments it. - -## Goals - -- Simple keyboard-driven TUI. -- Logical, revisitable configuration stages. -- A complete installation plan and explicit confirmation before anything - destructive happens. -- Logs for every backend operation. -- No magical hidden disk modifications. - -## Two layers - -``` -tui/ front-end: menus, dialogs, screens - menu.sh main loop, review and install flow - screens.sh one function per configuration stage - ui.sh dialog/whiptail abstraction - -lib/ deterministic backend (usable without the TUI) - state.sh structured configuration state - logging.sh logging + run_cmd + dry-run - confirm.sh destructive-operation authorization gates - hardware.sh read-only hardware probing - disks.sh read-only disk discovery and protection rules - partitions.sh GPT partitioning - filesystem.sh mkfs, mount, fstab/crypttab generation - encryption.sh LUKS2 - btrfs.sh subvolume layout - network.sh live networking + target hostname - portage.sh Portage configuration and stage3 - pkgpolicy.sh compile-vs-binary policy - kernel.sh kernel profile and installation - boot.sh systemd-boot (BLS entries) + dracut initramfs - users.sh accounts, passwords, sudo - desktop.sh desktop profiles - ai.sh assistant and structured proposals - opencode.sh pinned, checksum-verified OpenCode - plan.sh installation plan generation - validation.sh configuration validation - install.sh staged orchestration - -config/ - defaults.conf all defaults - opencode.manifest pinned OpenCode release + SHA-256 - -tests/ unit tests, no root or disks required -``` - -## Running in a Gentoo Live environment - -The LiveGUI reference (or any Gentoo live medium with `dialog`, Portage and the -disk tools listed in `doc/FINDINGS.md`) can run the installer directly: - -```sh -sudo /path/to/installer/bin/ai-installer -``` - -Useful non-interactive modes (the backend works without the TUI): - -```sh -# Print the generated installation plan and validate the configuration -ai-installer --plan - -# Load a saved configuration -ai-installer --config /root/phoebus-install.conf - -# Dry run: every command is logged, nothing is executed -ai-installer --dry-run - -# Run the backend without a TUI (still requires explicit ERASE confirmation) -ai-installer --config /root/phoebus-install.conf --install - -# Fetch and verify the pinned OpenCode release -ai-installer --bootstrap-opencode -``` - -### Typical flow - -1. Network (connect Wi-Fi if needed). -2. Keyboard, hostname, locale, timezone, user. -3. Disk: pick a target (protected devices are never offered). -4. Filesystem / encryption: LUKS2 is the default; set a passphrase. -5. Boot / kernel / packages / desktop as desired. -6. Review configuration -> inspect the plan. -7. Install -> read the destructive summary, type `ERASE`, confirm again. - -## Safety model - -- Detection never modifies a disk. -- The target disk must be explicitly selected from candidates. -- Disks that are mounted, read-only, optical/loop, or back the live medium are - marked **PROTECTED** and cannot be selected. -- All destructive commands go through `run_destructive`, which refuses to run - unless `PHOEBUS_DESTRUCTIVE_AUTHORIZED=yes`. Only `install.sh` grants this, - only after the plan is approved. -- Whole-disk erase additionally requires typing `ERASE`. -- Dry-run mode redirects all file writes to a temporary sandbox and runs no - commands. -- Passwords, passphrases and API keys are never written to the config or logs. - -## Package policy - -`lib/pkgpolicy.sh` implements the rule "compile when cheap or beneficial, use a -binary when expensive and the benefit is negligible". It is deterministic and -uses a curated table plus optional historical compile times -(`$STATE_DIR/compile-times.tsv`). No model is consulted to guess performance. - -## AI policy - -- The normal install path is fully deterministic and LLM-free. -- The AI assistant explains hardware, disks, filesystems, kernel and package - choices, and can translate a natural-language request into a **structured - proposal** (flat JSON with a fixed key whitelist). -- Every proposed field is validated by `lib/validation.sh`. The LLM never - receives secrets, never touches a disk and never runs a command. -- Proposal flow: request -> proposal -> validation -> preview -> confirmation -> - backend. - -See `doc/FINDINGS.md` for environment findings and `doc/TESTING.md` for safe -testing instructions. diff --git a/installer/bin/ai-installer b/installer/bin/ai-installer deleted file mode 100755 index afc1369..0000000 --- a/installer/bin/ai-installer +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Phoebus OS installer entry point. -# -# Usage: -# ai-installer start the text UI -# ai-installer --dry-run start the UI with no disk changes -# ai-installer --config FILE load a saved configuration -# ai-installer --plan print the installation plan and exit -# ai-installer --install run the deterministic backend (no TUI) -# ai-installer --yes skip interactive confirmations (unattended) -# ai-installer --luks-passphrase-file FILE -# ai-installer --user-password-file FILE -# ai-installer --root-password-file FILE -# ai-installer --bootstrap-opencode -# -# The deterministic backend can be used without the TUI. The TUI is only a -# front-end over the same configuration state and backend functions. -# Secret files must be mode 0600; their contents are never logged. - -PHOEBUS_VERSION="0.1.0" - -set -uo pipefail - -# Locate the project root (the directory containing lib/, tui/, config/). -_self="${BASH_SOURCE[0]}" -while [[ -L "$_self" ]]; do - _self="$(readlink "$_self")" -done -PHOEBUS_ROOT="$(cd "$(dirname "$_self")/.." && pwd)" -export PHOEBUS_ROOT - -CONFIG_FILE="" -MODE="tui" -UI_BACKEND="${UI_BACKEND:-auto}" -STATE_DIR="${STATE_DIR:-/run/ai-installer}" -LUKS_PW_FILE="" -USER_PW_FILE="" -ROOT_PW_FILE="" - -# read_secret_file FILE - read a secret without echoing it; returns non-zero -# when the file is missing or unreadable. The value is never logged. -read_secret_file() { - local file="$1" - [[ -r "$file" ]] || { printf 'cannot read secret file: %s\n' "$file" >&2; return 1; } - local value - value="$(cat -- "$file")" - printf '%s' "${value%$'\n'}" -} - -# --- argument parsing ------------------------------------------------------- -while (($#)); do - case "$1" in - --dry-run) CLI_DRY_RUN=yes ;; - --yes|-y) CLI_ASSUME_YES=yes ;; - --config) shift; CONFIG_FILE="${1:-}" ;; - --plan) MODE="plan" ;; - --install) MODE="install" ;; - --backend) MODE="plan" ;; - --ui) shift; UI_BACKEND="${1:-}" ;; - --luks-passphrase-file) shift; LUKS_PW_FILE="${1:-}" ;; - --user-password-file) shift; USER_PW_FILE="${1:-}" ;; - --root-password-file) shift; ROOT_PW_FILE="${1:-}" ;; - --bootstrap-opencode) MODE="opencode" ;; - --version|-V) printf '%s %s\n' "Phoebus installer" "$PHOEBUS_VERSION"; exit 0 ;; - --help|-h) - sed -n '3,20p' "$_self" | sed 's/^# \{0,1\}//' - exit 0 ;; - *) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;; - esac - shift -done - -export UI_BACKEND - -# --- load libraries --------------------------------------------------------- -# shellcheck source=/dev/null -for lib in state logging confirm hardware disks validation plan pkgpolicy \ - portage partitions filesystem encryption btrfs network kernel boot \ - users desktop opencode ai install; do - source "$PHOEBUS_ROOT/lib/$lib.sh" -done -# shellcheck source=/dev/null -for tui in ui screens menu; do - source "$PHOEBUS_ROOT/tui/$tui.sh" -done - -# --- initialize state ------------------------------------------------------- -mkdir -p "$STATE_DIR" 2>/dev/null || STATE_DIR="/tmp/ai-installer" -export STATE_DIR - -config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf" -[[ -n "$CONFIG_FILE" ]] && config_load_file "$CONFIG_FILE" - -[[ -n "${CLI_DRY_RUN:-}" ]] && config_set DRY_RUN "$CLI_DRY_RUN" -[[ -n "${CLI_ASSUME_YES:-}" ]] && config_set ASSUME_YES "$CLI_ASSUME_YES" - -log_init - -# --- load secrets from files (unattended installs only) --------------------- -if [[ -n "$LUKS_PW_FILE" ]]; then - LUKS_PASSPHRASE="$(read_secret_file "$LUKS_PW_FILE")" || exit 1 - secret_register "$LUKS_PASSPHRASE" -fi -if [[ -n "$USER_PW_FILE" ]]; then - USER_PASSWORD="$(read_secret_file "$USER_PW_FILE")" || exit 1 - secret_register "$USER_PASSWORD" -fi -if [[ -n "$ROOT_PW_FILE" ]]; then - ROOT_PASSWORD="$(read_secret_file "$ROOT_PW_FILE")" || exit 1 - secret_register "$ROOT_PASSWORD" -fi - -# --- run -------------------------------------------------------------------- -case "$MODE" in - plan) - plan_generate - plan_render - printf '\n' - printf 'Validation:\n' - problems="$(validate_config)" - if [[ -z "$problems" ]]; then printf ' OK\n'; else printf '%s\n' "$problems" | sed 's/^/ - /'; fi - exit 0 - ;; - install) - plan_generate - if [[ -n "$(validate_config)" ]]; then - log_error "configuration is incomplete; run --plan to inspect" - exit 1 - fi - if ! confirm_erase "$(plan_destructive_preview)"; then - log_error "installation not confirmed" - exit 1 - fi - destructive_grant - rc=0 - install_run || rc=$? - destructive_revoke - exit "$rc" - ;; - opencode) - if opencode_ensure; then - printf 'OpenCode ready at %s\n' "$(opencode_detect)" - exit 0 - fi - exit 1 - ;; - tui) - if ! ui_init; then - printf 'No dialog/whiptail found. Use --plan or --install for the backend.\n' >&2 - exit 1 - fi - menu_main - exit 0 - ;; -esac diff --git a/installer/config/defaults.conf b/installer/config/defaults.conf deleted file mode 100644 index 7aae67f..0000000 --- a/installer/config/defaults.conf +++ /dev/null @@ -1,83 +0,0 @@ -# Phoebus OS installer defaults. -# -# This file is sourced by lib/state.sh. Only settings that are not already -# defined are applied, so a user-supplied config file always wins. -# -# Do NOT put secrets (passwords, passphrases, API keys) in this file. - -# --- identity --------------------------------------------------------------- -config_default DISTRO_NAME "Phoebus OS" -config_default DISTRO_ID "phoebus" -config_default ARCH "x86_64" - -# --- general installation --------------------------------------------------- -config_default HOSTNAME "phoebus" -config_default KEYMAP "us" -config_default LOCALE "en_US.UTF-8" -config_default TIMEZONE "UTC" -config_default ROOT_SHELL "/bin/bash" - -# --- user account ----------------------------------------------------------- -config_default USERNAME "" -config_default USER_FULLNAME "Phoebus User" -config_default USER_GROUPS "wheel,audio,video,input,render,plugdev,libinput,network,power" -config_default USER_HOME "/home" - -# --- target / storage ------------------------------------------------------- -config_default TARGET_DISK "" -config_default PARTITION_SCHEME "whole_disk" -config_default EFI_SIZE_MIB "1024" -config_default EFI_MOUNT "/efi" -config_default SWAP_SIZE_MIB "0" # 0 = swapfile sized from RAM -config_default FILESYSTEM "btrfs" -config_default BTRFS_LABEL "phoebus" -config_default COMPRESS "zstd:3" -config_default INSTALL_ROOT "/mnt/phoebus" -config_default BTRFS_SUBVOLS "@ @home @var @snapshots @swap" - -# --- encryption ------------------------------------------------------------- -config_default ENCRYPTION "luks2" -config_default LUKS_NAME "cryptroot" -config_default LUKS_CIPHER "aes-xts-plain64" -config_default LUKS_KEY_SIZE "512" -config_default LUKS_PBKDF "argon2id" - -# --- Gentoo base installation ---------------------------------------------- -# Pin STAGE3_URL/STAGE3_SHA256 for reproducible installs. When empty the -# installer resolves the current stable systemd stage3 from the mirror. -config_default STAGE3_URL "" -config_default STAGE3_SHA256 "" -config_default STAGE3_MIRROR "https://distfiles.gentoo.org/releases/amd64/autobuilds" -config_default GENTOO_PROFILE "default/linux/amd64/23.0/systemd" -config_default BINHOST_URI "https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64" - -# --- boot / kernel ---------------------------------------------------------- -config_default BOOTLOADER "systemd-boot" -config_default KERNEL_PROFILE "optimized" # safe | optimized | aggressive -config_default KERNEL_PACKAGE "sys-kernel/gentoo-kernel" -config_default KERNEL_UKI "no" -config_default KERNEL_CONSOLE "console=tty0" -config_default KEEP_KERNELS "3" -config_default SECUREBOOT "no" - -# --- software --------------------------------------------------------------- -config_default PACKAGE_POLICY "balanced" # source_first | balanced | binary_first -config_default FEATURES_BINPKG "yes" -config_default ACCEPT_LICENSE "@FREE @BINARY-REDISTRIBUTABLE" -config_default DESKTOP_PROFILE "none" # none | minimal | dwl | full -config_default FLATPAK "no" -config_default AUDIO_STACK "pipewire" -config_default INIT_SYSTEM "systemd" - -# --- AI --------------------------------------------------------------------- -config_default AI_ENABLED "no" -config_default AI_PROVIDER "" -config_default AI_MODEL "" -config_default AI_ENDPOINT "" -config_default OPENCODE_VERSION "" -config_default OPENCODE_VERIFY "yes" - -# --- runtime (not persisted by default) ------------------------------------ -config_default DRY_RUN "no" -config_default ASSUME_YES "no" -config_default LOG_DIR "/var/log/ai-installer" diff --git a/installer/config/example.conf b/installer/config/example.conf deleted file mode 100644 index 74c0805..0000000 --- a/installer/config/example.conf +++ /dev/null @@ -1,46 +0,0 @@ -# Example Phoebus OS installer configuration. -# -# Load with: ai-installer --config example.conf -# Inspect: ai-installer --config example.conf --plan -# Install: ai-installer --config example.conf --install -# -# NEVER put passwords, passphrases or API keys in this file. They are prompted -# for interactively and are never persisted. - -# Identity -HOSTNAME='phoebus' -KEYMAP='us' -LOCALE='en_US.UTF-8' -TIMEZONE='UTC' - -# User -USERNAME='phoebus' -USER_FULLNAME='Phoebus User' - -# Storage -TARGET_DISK='/dev/nvme0n1' -PARTITION_SCHEME='whole_disk' -EFI_SIZE_MIB='1024' -FILESYSTEM='btrfs' -ENCRYPTION='luks2' -COMPRESS='zstd:3' - -# Boot and kernel -BOOTLOADER='systemd-boot' -KERNEL_PROFILE='optimized' -KERNEL_UKI='yes' -KEEP_KERNELS='3' - -# Packages -PACKAGE_POLICY='balanced' -FEATURES_BINPKG='yes' -ACCEPT_LICENSE='@FREE @BINARY-REDISTRIBUTABLE' - -# Desktop -DESKTOP_PROFILE='dwl' -FLATPAK='yes' - -# AI (credentials are provided separately, never here) -AI_ENABLED='no' -AI_PROVIDER='' -AI_MODEL='' diff --git a/installer/config/opencode.manifest b/installer/config/opencode.manifest deleted file mode 100644 index 130eff9..0000000 --- a/installer/config/opencode.manifest +++ /dev/null @@ -1,23 +0,0 @@ -# Pinned OpenCode release for the Phoebus OS installer. -# -# We deliberately do NOT use the vendor's curl|sh installer. The artifacts are -# fetched from the official GitHub release and verified against the SHA-256 -# digests below before anything is executed. -# -# Update procedure: -# 1. pick a release: https://github.com/anomalyco/opencode/releases -# 2. download the linux tarball for the architecture -# 3. sha256sum the tarball and update this file -# 4. test in a throwaway VM before shipping a new ISO - -VERSION=v1.18.31 - -# x86_64 (glibc) -x86_64.url=https://github.com/anomalyco/opencode/releases/download/v1.18.31/opencode-linux-x64.tar.gz -x86_64.sha256=e9312be75ed803b7415fc2aeabda1f4fe938912a39673762dc0c38c0e11ebde4 -x86_64.binary=opencode - -# aarch64 (glibc) -aarch64.url=https://github.com/anomalyco/opencode/releases/download/v1.18.31/opencode-linux-arm64.tar.gz -aarch64.sha256=0000000000000000000000000000000000000000000000000000000000000000 -aarch64.binary=opencode diff --git a/installer/doc/TESTING.md b/installer/doc/TESTING.md deleted file mode 100644 index 521a3d4..0000000 --- a/installer/doc/TESTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# Testing the installer safely - -Never test destructive paths on a real machine. There are three levels, from -cheapest to most realistic. - -## 1. Unit tests (no root, no disks) - -```sh -installer/tests/run_tests.sh -``` - -These cover configuration state, validation, plan generation, package policy, -OpenCode checksum verification, AI proposal parsing/whitelisting, the -destructive authorization gate, and the dry-run storage/sandbox behaviour. -They run on any Linux machine with Bash 4+; the development host has neither -`dialog` nor any Portage tooling, which is exactly the point. - -## 2. Dry-run - -```sh -installer/bin/ai-installer --dry-run --config my.conf -# or, without the TUI: -installer/bin/ai-installer --dry-run --config my.conf --plan -``` - -In dry-run mode: - -- `run_cmd` logs every command as `[dry-run]` and executes nothing; -- the target root becomes `$STATE_DIR/dry-run-root`, so even file generation - cannot touch the host; -- `install_preflight` still refuses incomplete or unsafe configurations. - -## 3. Full VM test (recommended before release) - -`tests/vm/run-vm.sh` boots the reference ISO with a **disposable** qcow2 disk: - -```sh -# defaults: 32 GiB disk, 4 GiB RAM, 4 CPUs, UEFI (OVMF) -installer/tests/vm/run-vm.sh --iso /path/to/livegui-amd64.iso - -# see all options -installer/tests/vm/run-vm.sh --help -``` - -Inside the VM: - -1. Boot the live medium and get a shell. -2. Copy or mount the `installer/` tree into the VM. -3. Run `bin/ai-installer`. -4. Select the virtio disk (`/dev/vda`) as the target. The ISO device is - protected and will not be offered. -5. Complete the review, type `ERASE`, and install. -6. Reboot the VM from the disk (`-boot c`) to verify UEFI boot, LUKS unlock and - the login. - -The script keeps the disk image in a working directory you choose, so a test -can be discarded by deleting that directory. It never touches host disks and -uses QEMU user-mode networking by default. - -## Additional checks - -- `bash -n` over every script is part of the unit suite (`test_syntax.sh`). -- `shellcheck` is optional and not required; several modules use constructs - that trip naive shellcheck rules, so treat its output as advisory. -- To exercise the backend without a VM, point `--config` at a file with - `TARGET_DISK` unset and use `--plan`; the safety tests already cover the - sandbox and authorization logic. diff --git a/installer/lib/ai.sh b/installer/lib/ai.sh deleted file mode 100644 index e245380..0000000 --- a/installer/lib/ai.sh +++ /dev/null @@ -1,301 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# AI assistant integration. -# -# Design rule: the LLM NEVER manipulates disks and NEVER runs privileged -# commands. It may only produce a structured proposal (a flat JSON object). -# The deterministic backend validates every field, the change is previewed and -# the user must confirm. Most assistant features work with no LLM at all. -# -# Secrets (API keys, passphrases, passwords) are never passed to the model and -# never written to the installation log. - -# --------------------------------------------------------------------------- -# Deterministic (offline) assistance -# --------------------------------------------------------------------------- - -ai_explain_hardware() { - { - printf 'Detected hardware\n' - printf '=================\n\n' - hw_report - printf '\nRecommended kernel profile: %s\n' "$(hw_recommended_kernel_profile)" - printf 'Suggested VIDEO_CARDS: %s\n' "$(portage_detect_video_cards)" - } 2>&1 -} - -ai_explain_disks() { - { - printf 'Disk summary\n' - printf '============\n\n' - local d - for d in "${DISK_LIST[@]}"; do - printf '%s\n' "$(disk_display_line "$d")" - done - printf '\nReading (read-only):\n' - if [[ -n "$(config_get TARGET_DISK)" && -b "$(config_get TARGET_DISK)" ]]; then - disk_layout_text "$(config_get TARGET_DISK)" - else - printf ' no target disk selected yet\n' - fi - } 2>&1 -} - -ai_explain_plan() { - plan_generate - plan_render -} - -ai_explain_encryption() { - cat <<'EOF' -Encryption and filesystem choices -================================= - -LUKS2 (default) - The whole root partition is encrypted. Unlocking happens at boot with a - passphrase. TPM2 enrollment is planned but not required. - -Btrfs subvolumes - @ the root filesystem - @home /home, snapshotted independently - @var /var, kept separate so root snapshots stay small - @snapshots /.snapshots, where rollback snapshots live - @swap holds the swapfile - - Separate subvolumes let snapshots and rollbacks target only the parts of - the system you care about, and keep user data out of root snapshots. - -zstd compression - Transparent compression at level 3. A good balance of CPU and space. -EOF -} - -# ai_offline_response QUERY - small deterministic help based on keywords -ai_offline_response() { - local q - q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" - case "$q" in - *partition*|*disk*|*layout*) ai_explain_disks ;; - *encrypt*|*luks*|*btrfs*|*filesystem*) ai_explain_encryption ;; - *hardware*|*cpu*|*gpu*|*wifi*|*bluetooth*) ai_explain_hardware ;; - *kernel*) printf 'Kernel policy\n=============\n\nProfile: %s\nPackage: %s\n\n%s\n' \ - "$(config_get KERNEL_PROFILE)" "$(kernel_select_package)" \ - "The distribution kernel is used as a stable, complete base. The installer applies conservative config fragments; it never generates a minimal kernel that only boots the current hardware." ;; - *package*|*compile*|*binary*) pkgpolicy_report ;; - *plan*|*summary*) ai_explain_plan ;; - *log*|*error*|*fail*) log_tail 60 ;; - *network*|*internet*) network_status_text ;; - *desktop*|*wayland*|*dwl*) printf 'Desktop\n=======\nProfile: %s\n\nBase: dwl (Wayland tiling). Audio: PipeWire + Wireplumber.\nFlatpak: %s\n' \ - "$(config_get DESKTOP_PROFILE)" "$(config_get FLATPAK)" ;; - *) printf 'I can explain (offline, no model required):\n' - printf ' - hardware: detected CPU/GPU/storage/network\n' - printf ' - disks: devices and read-only layout\n' - printf ' - encryption: LUKS2 and Btrfs subvolumes\n' - printf ' - kernel: kernel policy\n' - printf ' - packages: compile vs binary policy\n' - printf ' - plan: the generated installation plan\n' - printf ' - logs: recent installer log lines\n' - printf '\nAsk about any of these, or configure a model for free-form help.\n' - ;; - esac -} - -# --------------------------------------------------------------------------- -# Structured proposals -# --------------------------------------------------------------------------- -# Only these keys may be changed by an AI proposal, and every value is -# validated by validation.sh before it is accepted. -AI_PROPOSAL_KEYS=(TARGET_DISK ENCRYPTION FILESYSTEM DESKTOP_PROFILE - PACKAGE_POLICY KERNEL_PROFILE HOSTNAME TIMEZONE LOCALE KEYMAP USERNAME) - -# ai_parse_json_kv TEXT - flatten a flat JSON object into key=value lines -ai_parse_json_kv() { - local text="$1" match - while IFS= read -r match; do - [[ -z "$match" ]] && continue - if [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*\"([^\"]*)\"$ ]]; then - printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" - elif [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*([0-9]+|true|false)$ ]]; then - printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" - fi - done < <(grep -oE '"[A-Za-z_][A-Za-z0-9_]*"[[:space:]]*:[[:space:]]*("[^"]*"|[0-9]+|true|false)' <<<"$text") -} - -ai_key_allowed() { - local key="$1" k - for k in "${AI_PROPOSAL_KEYS[@]}"; do - [[ "$k" == "$key" ]] && return 0 - done - return 1 -} - -# ai_validate_field KEY VALUE - non-empty error string when invalid -ai_validate_field() { - local key="$1" value="$2" - case "$key" in - TARGET_DISK) validate_target_disk "$value" ;; - ENCRYPTION) [[ "$value" =~ ^(none|luks2)$ ]] || printf 'encryption must be none or luks2\n' ;; - FILESYSTEM) [[ "$value" =~ ^(btrfs|ext4)$ ]] || printf 'filesystem must be btrfs or ext4\n' ;; - DESKTOP_PROFILE) [[ " $(desktop_profiles) " == *" $value "* ]] || printf 'unknown desktop profile\n' ;; - PACKAGE_POLICY) [[ "$value" =~ ^(source_first|balanced|binary_first)$ ]] || printf 'unknown package policy\n' ;; - KERNEL_PROFILE) [[ "$value" =~ ^(safe|optimized|aggressive)$ ]] || printf 'unknown kernel profile\n' ;; - HOSTNAME) validate_hostname "$value" ;; - TIMEZONE) validate_timezone "$value" ;; - LOCALE) validate_locale "$value" ;; - KEYMAP) validate_keymap "$value" ;; - USERNAME) validate_username "$value" ;; - *) printf 'key not permitted\n' ;; - esac -} - -# ai_apply_proposal TEXT - validate and apply; print accepted/rejected lines. -# Nothing is executed; only configuration state is changed. -ai_apply_proposal() { - local text="$1" line key value err accepted=0 rejected=0 - printf 'AI proposal review\n==================\n\n' - while IFS= read -r line; do - key="${line%%=*}"; value="${line#*=}" - key="${key^^}" - if ! ai_key_allowed "$key"; then - printf 'REJECTED %-16s %s (not a permitted setting)\n' "$key" "$value" - rejected=$((rejected+1)); continue - fi - err="$(ai_validate_field "$key" "$value")" - if [[ -n "$err" ]]; then - printf 'REJECTED %-16s %s (%s)\n' "$key" "$value" "${err%%$'\n'*}" - rejected=$((rejected+1)); continue - fi - printf 'ACCEPTED %-16s %s\n' "$key" "$value" - config_set "$key" "$value" - accepted=$((accepted+1)) - done < <(ai_parse_json_kv "$text") - printf '\n%d accepted, %d rejected.\n' "$accepted" "$rejected" - log_info "AI proposal applied: $accepted accepted, $rejected rejected" - ((rejected == 0)) -} - -# ai_propose_offline QUERY - deterministic translator for common requests -ai_propose_offline() { - local q - q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" - local json="{" - local sep="" - if [[ "$q" == *encrypt* || "$q" == *luks* ]]; then - json+="${sep}\"encryption\":\"luks2\""; sep="," - fi - if [[ "$q" == *btrfs* ]]; then - json+="${sep}\"filesystem\":\"btrfs\""; sep="," - fi - if [[ "$q" == *desktop* ]]; then - json+="${sep}\"desktop_profile\":\"dwl\""; sep="," - elif [[ "$q" == *minimal* ]]; then - json+="${sep}\"desktop_profile\":\"minimal\""; sep="," - fi - local disk - disk="$(printf '%s' "$q" | grep -oE '/dev/(nvme[0-9]+n[0-9]+|[sv]d[a-z])' | head -n1)" - if [[ -n "$disk" ]]; then - if disks_is_protected "$disk"; then - printf 'Offline assistant: %s looks protected, not proposing it.\n' "$disk" >&2 - else - json+="${sep}\"target_disk\":\"$disk\""; sep="," - fi - fi - json+="}" - printf '%s\n' "$json" -} - -# ai_propose_llm QUERY - ask OpenCode for a flat JSON proposal. -# The result is only ever fed to ai_apply_proposal, which validates everything. -ai_propose_llm() { - local query="$1" bin prompt out - bin="$(opencode_detect)" || { log_warn "OpenCode not available"; return 1; } - prompt="You are the Phoebus OS installer assistant. Reply with ONLY a flat JSON object of installer settings. Allowed keys: ${AI_PROPOSAL_KEYS[*]}. Allowed values: encryption=none|luks2, filesystem=btrfs|ext4, desktop_profile=none|minimal|dwl|full, package_policy=source_first|balanced|binary_first, kernel_profile=safe|optimized|aggressive. Do not include markdown, explanations, commands, shell code or secrets. User request: $query" - log_info "AI: requesting structured proposal from OpenCode" - out="$("$bin" run --pure "$prompt" 2>>"$PHOEBUS_LOG_FILE")" || { - log_error "OpenCode run failed"; return 1; } - printf '%s\n' "$out" -} - -# ai_propose_interactive - choose engine, then apply validated proposal -ai_propose_interactive() { - local query engine text - if declare -F ui_inputbox >/dev/null 2>&1; then - ui_inputbox "AI proposal" "Describe the installation you want (e.g. 'whole nvme, encrypt everything, desktop')." "" || return 1 - query="$UI_RESULT" - else - printf 'Describe the installation you want: ' >&2 - read -r query || return 1 - fi - [[ -n "$query" ]] || return 1 - - engine="offline" - if opencode_available && config_bool AI_ENABLED; then - if declare -F ui_menu >/dev/null 2>&1; then - ui_menu "AI proposal" "Which engine should translate the request?" 10 60 2 \ - offline "Deterministic rules (no model)" \ - model "OpenCode model (validated proposal)" || return 1 - engine="$UI_RESULT" - fi - fi - - if [[ "$engine" == "model" ]]; then - text="$(ai_propose_llm "$query")" || return 1 - else - text="$(ai_propose_offline "$query")" - fi - log_info "AI proposal text: $text" - ai_apply_proposal "$text" || log_warn "some proposed settings were rejected" - return 0 -} - -# ai_store_api_key KEY - store a provider key with restrictive permissions -ai_store_api_key() { - local key="$1" dir file - dir="${STATE_DIR:-/tmp/ai-installer}/ai" - file="$dir/credentials" - mkdir -p "$dir" - secret_register "$key" - umask 077 - printf '%s\n' "$key" >"$file" - chmod 0600 "$file" - log_info "API credential stored at $file (value not logged)" -} - -# ai_configure - provider/model setup; secrets never logged -ai_configure() { - local provider model endpoint key - if declare -F ui_inputbox >/dev/null 2>&1; then - ui_inputbox "AI configuration" "Provider (e.g. anthropic, openai, ollama):" "$(config_get AI_PROVIDER)" || return 1 - provider="$UI_RESULT" - ui_inputbox "AI configuration" "Model (e.g. claude-sonnet-4, gpt-5, llama3):" "$(config_get AI_MODEL)" || return 1 - model="$UI_RESULT" - ui_inputbox "AI configuration" "Custom endpoint / base URL (optional, for local models):" "$(config_get AI_ENDPOINT)" || return 1 - endpoint="$UI_RESULT" - config_set AI_PROVIDER "$provider" - config_set AI_MODEL "$model" - config_set AI_ENDPOINT "$endpoint" - config_set AI_ENABLED "yes" - opencode_write_config - - if declare -F ui_yesno >/dev/null 2>&1; then - if ui_yesno "AI credentials" "Store an API key now? It is saved with mode 0600 and never logged."; then - ui_passwordbox "AI credentials" "Paste API key (input hidden):" || return 0 - key="$UI_RESULT" - ai_store_api_key "$key" - fi - fi - else - printf 'AI configuration requires the TUI or a config file.\n' - fi - return 0 -} - -# ai_status_text -ai_status_text() { - printf 'AI assistant: %s\n' "$(config_bool AI_ENABLED && echo enabled || echo disabled)" - printf 'OpenCode: %s\n' "$(opencode_detect || echo 'not installed')" - printf 'Provider: %s\n' "$(config_get AI_PROVIDER)" - printf 'Model: %s\n' "$(config_get AI_MODEL)" - printf 'Endpoint: %s\n' "$(config_get AI_ENDPOINT)" -} diff --git a/installer/lib/boot.sh b/installer/lib/boot.sh deleted file mode 100644 index 184af05..0000000 --- a/installer/lib/boot.sh +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Bootloader installation (UEFI + systemd-boot, Unified Kernel Images). -# -# The ESP is mounted in the target at EFI_MOUNT. systemd-boot is installed and -# configured to boot UKIs produced by kernel-install. Secure Boot is scaffolded -# but not enforced in v0.1. - -boot_esp_path() { - printf '%s%s' "$1" "$(config_get EFI_MOUNT)" -} - -# boot_install ROOT - install systemd-boot into the ESP -boot_install() { - local root="$1" esp - esp="$(config_get EFI_MOUNT)" - portage_chroot "$root" bootctl --esp-path="$esp" install -} - -# boot_write_loader_conf ROOT -boot_write_loader_conf() { - local root="$1" esp dir - esp="$(boot_esp_path "$root")" - dir="$esp/loader" - mkdir -p "$dir" - { - printf '# systemd-boot configuration\n' - printf 'default *\n' - printf 'timeout %s\n' "3" - printf 'console-mode keep\n' - printf 'editor no\n' - } >"$dir/loader.conf" - log_info "wrote $dir/loader.conf" -} - -# boot_write_install_conf ROOT -# Configure Gentoo installkernel. v0.1 uses layout=bls (Boot Loader -# Specification): the kernel and dracut initramfs are placed on the ESP and -# systemd-boot entry files carry the kernel command line. The dracut UKI -# generator does not embed /etc/kernel/cmdline, which produced an unbootable -# image (no root=), so UKI is deferred until that path is verified. -boot_write_install_conf() { - local root="$1" dir - dir="$root/etc/kernel" - mkdir -p "$dir" - { - printf '# /etc/kernel/install.conf - Gentoo installkernel\n' - printf '# When /etc/kernel/install.conf exists it is used INSTEAD of the\n' - printf '# package default in /usr/lib/kernel/install.conf, so every required\n' - printf '# generator must be listed here.\n' - printf '# installkernel always requires uki_generator when dracut generates\n' - printf '# the initramfs; "none" disables UKI assembly for the BLS layout.\n' - printf 'layout=bls\n' - printf 'initrd_generator=dracut\n' - printf 'uki_generator=none\n' - } >"$dir/install.conf" - log_info "wrote $dir/install.conf (layout=bls)" -} - -# boot_write_dracut_conf ROOT -# A generic initramfs with the storage/crypto modules forced in. This keeps -# the encrypted Btrfs root unlockable and survives kernel updates. -boot_write_dracut_conf() { - local root="$1" - local dir="$root/etc/dracut.conf.d" - mkdir -p "$dir" - { - printf '# %s dracut configuration\n' "$(config_get DISTRO_NAME)" - printf '# Generic (non-hostonly) initramfs for predictable boot behaviour.\n' - printf 'hostonly="no"\n' - printf 'compress="zstd"\n' - printf 'add_dracutmodules+=" crypt btrfs "\n' - } >"$dir/10-phoebus.conf" - log_info "wrote $dir/10-phoebus.conf" -} - -# boot_generate_uki ROOT - trigger kernel-install for every installed kernel -boot_generate_uki() { - local root="$1" - portage_chroot "$root" kernel-install add-all -} - -# boot_install_fallback ROOT - ensure the default EFI fallback path works even -# when writing the UEFI boot variable failed. -boot_install_fallback() { - local root="$1" esp src - esp="$(boot_esp_path "$root")" - mkdir -p "$esp/EFI/BOOT" "$esp/EFI/systemd" - src="$esp/EFI/systemd/systemd-bootx64.efi" - if [[ ! -e "$src" ]]; then - # Boot loader provided by sys-apps/systemd[boot] inside the target. - local vendor="$root/usr/lib/systemd/boot/efi/systemd-bootx64.efi" - if [[ -e "$vendor" ]]; then - src="$vendor" - else - log_warn "systemd-boot binary not found; EFI fallback not installed" - return 1 - fi - fi - run_cmd "install fallback bootloader" cp -f "$src" "$esp/EFI/BOOT/BOOTX64.EFI" -} - -# boot_random_seed ROOT - enable systemd random seed persistence -boot_random_seed() { - local root="$1" esp - esp="$(boot_esp_path "$root")" - mkdir -p "$esp/loader" - if [[ ! -e "$esp/loader/random-seed" ]]; then - run_cmd "create random seed" \ - dd if=/dev/urandom of="$esp/loader/random-seed" bs=512 count=1 status=none - fi -} - -# boot_verify ROOT - confirm bootloader artifacts exist -boot_verify() { - local root="$1" esp - esp="$(boot_esp_path "$root")" - if [[ ! -e "$esp/EFI/systemd/systemd-bootx64.efi" && \ - ! -e "$esp/EFI/BOOT/BOOTX64.EFI" ]]; then - log_error "no systemd-boot loader found in $esp" - return 1 - fi - [[ -e "$esp/loader/loader.conf" ]] || { - log_error "loader.conf not found"; return 1; } - return 0 -} - -# boot_secureboot_status - report, never change firmware state -boot_secureboot_status() { - if [[ -d /sys/firmware/efi/efivars ]]; then - if command -v mokutil >/dev/null 2>&1; then - mokutil --sb-state 2>/dev/null || printf 'unknown' - else - printf 'Secure Boot state unknown (mokutil not installed)' - fi - else - printf 'not booted in UEFI mode' - fi -} - -# boot_secureboot_scaffold ROOT - placeholders for future enrollment -boot_secureboot_scaffold() { - local root="$1" - mkdir -p "$root/etc/secureboot" - { - printf '# Secure Boot is not enabled by this version of the installer.\n' - printf '# Future: sbctl / systemd-sbsign key enrollment and UKI signing.\n' - } >"$root/etc/secureboot/README" -} diff --git a/installer/lib/btrfs.sh b/installer/lib/btrfs.sh deleted file mode 100644 index 0511e4a..0000000 --- a/installer/lib/btrfs.sh +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Btrfs layout backend. -# -# Default layout (see config/defaults.conf): -# @ / root -# @home /home -# @var /var -# @snapshots /.snapshots -# @swap /swap holds the swapfile -# -# Top-level (subvolid=5) is only mounted temporarily to create subvolumes. - -btrfs_require_tools() { - require_cmd btrfs mkfs.btrfs || return 1 -} - -btrfs_mount_opts() { - local opts - opts="noatime,compress=$(config_get COMPRESS),space_cache=v2" - if [[ "$(disk_transport "$(config_get TARGET_DISK)")" == "nvme" || \ - "$(disk_transport "$(config_get TARGET_DISK)")" == "sata" ]]; then - opts+=",ssd" - fi - printf '%s' "$opts" -} - -# btrfs_mkfs DEVICE -btrfs_mkfs() { - local dev="$1" label - label="$(config_get BTRFS_LABEL)" - run_destructive "create Btrfs filesystem on $dev" \ - mkfs.btrfs -f -L "$label" "$dev" -} - -# btrfs_mount_top DEVICE MOUNTPOINT -btrfs_mount_top() { - local dev="$1" mp="$2" - mkdir -p "$mp" - run_cmd "mount Btrfs top-level" mount -o "subvolid=5" "$dev" "$mp" -} - -# btrfs_create_subvolumes MOUNTPOINT -btrfs_create_subvolumes() { - local mp="$1" sv - for sv in $(config_get BTRFS_SUBVOLS); do - run_destructive "create subvolume $sv" btrfs subvolume create "$mp/$sv" || return 1 - done -} - -# btrfs_set_default MOUNTPOINT - make @ the default subvolume -btrfs_set_default() { - local mp="$1" id - id="$(btrfs subvolume list -o "$mp" 2>/dev/null | awk '$NF=="@"{print $2; exit}')" - [[ -n "$id" ]] || return 0 - run_cmd "set @ as default subvolume" btrfs subvolume set-default "$id" "$mp" -} - -# btrfs_mount_layout DEVICE ROOT -btrfs_mount_layout() { - local dev="$1" root="$2" opts - opts="$(btrfs_mount_opts)" - mkdir -p "$root" - run_cmd "mount @ at $root" mount -o "${opts},subvol=@" "$dev" "$root" || return 1 - local pair sv target - for pair in "@home:home" "@var:var" "@snapshots:.snapshots" "@swap:swap"; do - sv="${pair%%:*}"; target="${pair##*:}" - mkdir -p "$root/$target" - run_cmd "mount $sv at /$target" mount -o "${opts},subvol=$sv" "$dev" "$root/$target" || return 1 - done -} - -# btrfs_create_layout DEVICE ROOT -# Create the subvolume layout on a freshly created filesystem, then mount it. -# The top-level (subvolid=5) must be mounted to create @, @home, ...; only -# afterwards can the individual subvolumes be mounted. -btrfs_create_layout() { - local dev="$1" root="$2" - btrfs_mount_top "$dev" "$root" || return 1 - if ! btrfs_create_subvolumes "$root"; then - run_cmd "unmount top-level" umount "$root" || true - return 1 - fi - btrfs_set_default "$root" || true - run_cmd "unmount top-level" umount "$root" || return 1 - btrfs_mount_layout "$dev" "$root" -} - -# btrfs_create_swapfile ROOT [MIB] -btrfs_create_swapfile() { - local root="$1" mib="${2:-$(plan_swap_mib)}" - local swapdir="$root/swap" - mkdir -p "$swapdir" - if btrfs filesystem mkswapfile --help >/dev/null 2>&1; then - run_cmd "create Btrfs swapfile" \ - btrfs filesystem mkswapfile --size "${mib}m" "$swapdir/swapfile" - else - run_cmd "create swapfile container" \ - truncate -s "${mib}M" "$swapdir/swapfile" || return 1 - run_cmd "disable CoW on swapfile" chattr +C "$swapdir/swapfile" - run_cmd "make swap" mkswap "$swapdir/swapfile" - fi -} - -# btrfs_scrub_device DEVICE - verify checksums (non-destructive) -btrfs_scrub_device() { - run_cmd "scrub $1" btrfs scrub start -B "$1" -} diff --git a/installer/lib/confirm.sh b/installer/lib/confirm.sh deleted file mode 100644 index d76fa50..0000000 --- a/installer/lib/confirm.sh +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Destructive-operation confirmation infrastructure. -# -# There are two independent gates: -# -# 1. PHOEBUS_DESTRUCTIVE_AUTHORIZED must be "yes" before run_destructive will -# execute anything. Only install.sh sets it, and only after the user has -# approved the generated plan. -# 2. Whole-disk erase additionally requires the user to type the word ERASE. -# -# This means a bug in the TUI cannot silently wipe a disk: every destructive -# command goes through run_destructive. - -declare -g PHOEBUS_DESTRUCTIVE_AUTHORIZED="${PHOEBUS_DESTRUCTIVE_AUTHORIZED:-no}" - -destructive_authorized() { [[ "$PHOEBUS_DESTRUCTIVE_AUTHORIZED" == "yes" ]]; } - -# destructive_grant / destructive_revoke -destructive_grant() { PHOEBUS_DESTRUCTIVE_AUTHORIZED="yes"; log_warn "destructive operations AUTHORIZED for this session"; } -destructive_revoke() { PHOEBUS_DESTRUCTIVE_AUTHORIZED="no"; log_info "destructive operations revoked"; } - -# _prompt_yesno MESSAGE - returns 0 for yes -_prompt_yesno() { - local message="$1" - if declare -F ui_yesno >/dev/null 2>&1; then - ui_yesno "Confirm" "$message" - return $? - fi - local answer - printf '%s [y/N] ' "$message" >&2 - read -r answer || return 1 - [[ "$answer" =~ ^[Yy] ]] -} - -# _prompt_word PROMPT EXPECTED - returns 0 when the typed word matches -_prompt_word() { - local prompt="$1" expected="$2" answer - if declare -F ui_inputbox >/dev/null 2>&1; then - ui_inputbox "Destructive operation" "$prompt" "" || return 1 - answer="$UI_RESULT" - else - printf '%s ' "$prompt" >&2 - read -r answer || return 1 - fi - [[ "$answer" == "$expected" ]] -} - -# confirm_action MESSAGE - plain yes/no confirmation -confirm_action() { - if config_bool ASSUME_YES; then - log_warn "auto-approving (ASSUME_YES): $1" - return 0 - fi - _prompt_yesno "$1" -} - -# confirm_erase PREVIEW - strong confirmation for whole-disk destruction. -# Displays PREVIEW and requires the user to type ERASE. -confirm_erase() { - local preview="$1" - if config_bool ASSUME_YES; then - log_warn "auto-approving ERASE confirmation (ASSUME_YES)" - return 0 - fi - if declare -F ui_msgbox >/dev/null 2>&1; then - ui_msgbox "DESTRUCTIVE OPERATION" "$preview - -Type ERASE to continue." - else - printf '%s\n\n' "$preview" >&2 - fi - _prompt_word "Type ERASE to confirm:" "ERASE" -} - -# require_destructive_authorization CALLER - hard gate used by run_destructive -require_destructive_authorization() { - if ! destructive_authorized; then - log_error "blocked destructive operation from ${1:-unknown}: not authorized" - return 1 - fi - return 0 -} - -# run_destructive DESCRIPTION ARGS... -# Execute a previously approved destructive command. Honours DRY_RUN via -# run_cmd. Refuses to run without authorization. -run_destructive() { - local desc="${1:-destructive operation}"; shift - require_destructive_authorization "$desc" || return 1 - run_cmd "$desc" "$@" -} diff --git a/installer/lib/desktop.sh b/installer/lib/desktop.sh deleted file mode 100644 index cd9d402..0000000 --- a/installer/lib/desktop.sh +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Desktop profile installation. -# -# The flagship desktop is a small Wayland tiling environment centred on dwl. -# Full desktop installation is future work; this module defines the profile and -# the package sets so the installer can grow into it cleanly. - -desktop_profiles() { - printf '%s\n' none minimal dwl full -} - -# desktop_packages PROFILE -desktop_packages() { - local profile="$1" - case "$profile" in - none) - ;; - minimal) - printf '%s\n' \ - gui-libs/wayland \ - gui-libs/wayland-protocols \ - x11-base/xwayland - ;; - dwl|full) - printf '%s\n' \ - gui-wm/dwl \ - gui-apps/waybar \ - gui-apps/wofi \ - gui-apps/mako \ - gui-apps/swayidle \ - gui-apps/swaylock \ - gui-apps/swaybg \ - gui-apps/wl-clipboard \ - gui-apps/grim \ - gui-apps/slurp \ - gui-libs/gtk-layer-shell \ - x11-base/xwayland \ - x11-terms/kitty \ - net-misc/networkmanager \ - sys-auth/polkit \ - gnome-extra/polkit-gnome - ;; - esac - if [[ "$profile" == "full" ]]; then - printf '%s\n' \ - sys-apps/flatpak \ - net-wireless/bluez \ - gnome-base/gnome-keyring - fi -} - -# desktop_audio_packages - PipeWire is always the audio stack -desktop_audio_packages() { - printf '%s\n' media-video/pipewire media-video/wireplumber -} - -# desktop_install ROOT -desktop_install() { - local root="$1" profile - profile="$(config_get DESKTOP_PROFILE)" - [[ "$profile" == "none" ]] && { log_info "no desktop profile selected"; return 0; } - - local -a packages=() - mapfile -t packages < <(desktop_packages "$profile") - mapfile -t -O "${#packages[@]}" packages < <(desktop_audio_packages) - if config_bool FLATPAK; then - packages+=(sys-apps/flatpak) - fi - log_info "installing desktop profile '$profile' (${#packages[@]} packages)" - portage_emerge "$root" "${packages[@]}" -} - -# desktop_configure_flatpak ROOT -desktop_configure_flatpak() { - local root="$1" - config_bool FLATPAK || return 0 - # Flathub is a third-party catalogue; adding it is opt-in via the profile. - portage_chroot "$root" flatpak remote-add --if-not-exists flathub \ - https://flathub.org/repo/flathub.flatpakrepo || { - log_warn "could not add flathub remote (network?)"; return 0; } - log_info "flatpak configured with flathub" -} - -# desktop_services ROOT - system services needed by the desktop -desktop_services() { - local profile - profile="$(config_get DESKTOP_PROFILE)" - printf '%s\n' NetworkManager systemd-resolved - [[ "$profile" == "full" ]] && printf '%s\n' bluetooth - return 0 -} diff --git a/installer/lib/disks.sh b/installer/lib/disks.sh deleted file mode 100644 index 7c59e0e..0000000 --- a/installer/lib/disks.sh +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Read-only disk and partition discovery. -# -# This module never writes to a disk. It exists so the installer can present -# accurate information and so destructive operations can refuse to touch the -# live medium, mounted filesystems or optical drives. - -declare -ga DISK_LIST=() - -# disks_available_tool -disks_tool_ok() { command -v lsblk >/dev/null 2>&1; } - -# disks_refresh - populate DISK_LIST with whole-disk device paths -disks_refresh() { - DISK_LIST=() - disks_tool_ok || return 1 - local name path - while IFS= read -r name; do - path="/dev/$name" - [[ -b "$path" ]] && DISK_LIST+=("$path") - done < <(lsblk -dn -o NAME 2>/dev/null | sort) - ((${#DISK_LIST[@]})) -} - -# _disk_attr PATH COLUMN - single value for a whole disk -_disk_attr() { - local path="$1" col="$2" - lsblk -dn -o "$col" "$path" 2>/dev/null | head -n1 | sed 's/[[:space:]]*$//' -} - -disk_size_bytes() { - lsblk -bdn -o SIZE "$1" 2>/dev/null | head -n1 | tr -d ' ' -} -disk_size_human() { - local b="${1:-0}" - numfmt --to=iec --suffix=B "$b" 2>/dev/null || printf '%s bytes' "$b" -} -disk_model() { _disk_attr "$1" MODEL; } -disk_transport() { _disk_attr "$1" TRAN; } -disk_is_removable() { [[ "$(_disk_attr "$1" RM)" == "1" ]]; } -disk_is_readonly() { [[ "$(_disk_attr "$1" RO)" == "1" ]]; } - -# disk_partitions PATH - print child device paths one per line -disk_partitions() { - local path="$1" name - while IFS= read -r name; do - [[ -n "$name" ]] && printf '/dev/%s\n' "$name" - done < <(lsblk -rno NAME "$path" 2>/dev/null | tail -n +2) -} - -disk_partition_count() { - disk_partitions "$1" | grep -c . || true -} - -# disk_is_mounted PATH - true when the disk or any child is mounted -disk_is_mounted() { - local path="$1" dev - while IFS= read -r dev; do - [[ -n "$dev" ]] || continue - if grep -q "^${dev} " /proc/mounts 2>/dev/null; then - return 0 - fi - done < <(printf '%s\n' "$path"; disk_partitions "$path") - return 1 -} - -# _parent_disk DEV - resolve a device (possibly a partition) to its whole disk -_parent_disk() { - local dev="$1" pk - dev="$(readlink -f "$dev" 2>/dev/null || printf '%s' "$dev")" - case "$dev" in - /dev/loop*|/dev/dm-*|/dev/mapper/*|/dev/sr*) printf '%s' "$dev"; return ;; - esac - pk="$(lsblk -no PKNAME "$dev" 2>/dev/null | head -n1)" - if [[ -n "$pk" ]]; then printf '/dev/%s' "$pk"; else printf '%s' "$dev"; fi -} - -# _live_source_disks - whole disks that back the running live system -_live_source_disks() { - local src disk - local -a sources=() - # Sources directly referenced by the kernel command line. - if [[ -r /proc/cmdline ]]; then - while IFS= read -r tok; do - case "$tok" in - root=*|cdroot=*|boot=*) sources+=("${tok#*=}") ;; - esac - done < <(tr ' ' '\n' /dev/null)" - [[ -n "$src" ]] && sources+=("$src") - done - fi - local seen="" - for src in "${sources[@]}"; do - [[ -b "$src" ]] || continue - disk="$(_parent_disk "$src")" - case "$seen" in *" $disk "*) continue ;; esac - seen+=" $disk " - printf '%s\n' "$disk" - done -} - -# disk_protected_reason PATH - non-empty when the disk must not be a target -disk_protected_reason() { - local path="$1" live - if disk_is_readonly "$path"; then - printf 'read-only device' - return - fi - case "$path" in - /dev/sr*|/dev/loop*|/dev/dm-*|/dev/mapper/*) - printf 'not a whole disk' - return ;; - esac - if disk_is_mounted "$path"; then - printf 'contains mounted filesystems' - return - fi - while IFS= read -r live; do - if [[ "$live" == "$path" ]]; then - printf 'live installation medium' - return - fi - done < <(_live_source_disks) -} - -# disks_is_protected PATH -disks_is_protected() { [[ -n "$(disk_protected_reason "$1")" ]]; } - -# disks_candidates - device paths that may be chosen as installation target -disks_candidates() { - local d - for d in "${DISK_LIST[@]}"; do - disks_is_protected "$d" || printf '%s\n' "$d" - done -} - -# disk_display_line PATH - one line description for menus -disk_display_line() { - local path="$1" size model tran flag="" reason - size="$(disk_size_human "$(disk_size_bytes "$path")")" - model="$(disk_model "$path")" - tran="$(disk_transport "$path")" - reason="$(disk_protected_reason "$path")" - if [[ -n "$reason" ]]; then - flag=" [PROTECTED: $reason]" - fi - printf '%-16s %8s %-8s %s%s' "$path" "$size" "${tran:-?}" "${model:-disk}" "$flag" -} - -# disk_partition_table PATH - GPT/MBR/unknown via parted (read-only) -disk_partition_table() { - command -v parted >/dev/null 2>&1 || { printf 'unknown'; return; } - local out - out="$(parted -s "$1" print 2>/dev/null | awk -F': ' '/Partition Table/{print $2; exit}')" - printf '%s' "${out:-unknown}" -} - -# disk_free_space_bytes PATH - unpartitioned space, best effort -disk_free_space_bytes() { - command -v parted >/dev/null 2>&1 || return 1 - parted -s -m "$1" unit B print free 2>/dev/null | \ - awk -F: '$5=="free"{sum+=$4} END{printf "%d", sum}' -} - -# disk_layout_text PATH - read-only partition listing -disk_layout_text() { - local path="$1" - lsblk -o NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS "$path" 2>/dev/null -} diff --git a/installer/lib/encryption.sh b/installer/lib/encryption.sh deleted file mode 100644 index eedbc87..0000000 --- a/installer/lib/encryption.sh +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# LUKS2 encryption backend. -# -# Passphrases are held in memory only (LUKS_PASSPHRASE), never written to the -# config, never passed on a command line and never logged. cryptsetup reads the -# passphrase from stdin via --key-file -. -# -# TPM2 enrollment is intentionally not implemented in v0.1; the function -# stubs document where it will hook in. - -declare -g LUKS_PASSPHRASE="${LUKS_PASSPHRASE:-}" - -encryption_require_tools() { - require_cmd cryptsetup blkid || return 1 -} - -# encryption_configure - prompt for and remember the passphrase (TUI or tty) -encryption_configure() { - local first second - if declare -F ui_passwordbox >/dev/null 2>&1; then - ui_passwordbox "Encryption passphrase" "Enter a LUKS2 passphrase for the root volume:" || return 1 - first="$UI_RESULT" - ui_passwordbox "Encryption passphrase" "Repeat the passphrase:" || return 1 - second="$UI_RESULT" - else - read -r -s -p "LUKS passphrase: " first; printf '\n' >&2 - read -r -s -p "Repeat: " second; printf '\n' >&2 - fi - if [[ -z "$first" ]]; then - log_error "empty encryption passphrase refused" - return 1 - fi - if [[ "$first" != "$second" ]]; then - log_error "passphrases did not match" - return 1 - fi - LUKS_PASSPHRASE="$first" - secret_register "$first" - log_info "encryption passphrase set (value not logged)" - return 0 -} - -# _run_cryptsetup_stdin DESCRIPTION COMMAND... - feeds LUKS_PASSPHRASE on stdin -_run_cryptsetup_stdin() { - local desc="$1"; shift - if config_bool DRY_RUN; then - log_line INFO "[dry-run] $desc :: $(_cmd_to_string "$@")" - return 0 - fi - log_line INFO "$desc :: $(_cmd_to_string "$@")" - printf '%s' "$LUKS_PASSPHRASE" | "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 - local status=$? - log_line INFO "$desc :: exit status $status" - return $status -} - -# encryption_format PARTITION -encryption_format() { - local part="$1" cipher keysize pbkdf - cipher="$(config_get LUKS_CIPHER)" - keysize="$(config_get LUKS_KEY_SIZE)" - pbkdf="$(config_get LUKS_PBKDF)" - [[ -n "$LUKS_PASSPHRASE" ]] || { log_error "no passphrase configured"; return 1; } - _run_cryptsetup_stdin "format LUKS2 on $part" \ - cryptsetup luksFormat --batch-mode --type luks2 \ - --cipher "$cipher" --key-size "$keysize" --pbkdf "$pbkdf" \ - --key-file - "$part" -} - -# encryption_open PARTITION NAME -encryption_open() { - local part="$1" name="${2:-$(config_get LUKS_NAME)}" - [[ -n "$LUKS_PASSPHRASE" ]] || { log_error "no passphrase configured"; return 1; } - _run_cryptsetup_stdin "open LUKS2 $part as $name" \ - cryptsetup open --type luks --key-file - "$part" "$name" -} - -# encryption_close NAME -encryption_close() { - local name="${1:-$(config_get LUKS_NAME)}" - run_destructive "close LUKS device $name" cryptsetup close "$name" -} - -# encryption_mapper_path NAME -encryption_mapper_path() { - printf '/dev/mapper/%s' "${1:-$(config_get LUKS_NAME)}" -} - -# encryption_crypttab_line PARTITION [NAME] -# Produces a crypttab line using the partition UUID (stable across reboots). -encryption_crypttab_line() { - local part="$1" name="${2:-$(config_get LUKS_NAME)}" uuid - uuid="$(blkid -s UUID -o value "$part" 2>/dev/null)" - [[ -n "$uuid" ]] || return 1 - printf '%s UUID=%s none luks,discard\n' "$name" "$uuid" -} - -# encryption_tpm2_enroll - future work; never made mandatory -encryption_tpm2_enroll() { - log_warn "TPM2 enrollment is not implemented in this version" - return 1 -} - -# encryption_tpm2_available - best-effort capability probe -encryption_tpm2_available() { - [[ -e /sys/class/tpm/tpm0 ]] && command -v systemd-cryptenroll >/dev/null 2>&1 -} diff --git a/installer/lib/filesystem.sh b/installer/lib/filesystem.sh deleted file mode 100644 index e506cf2..0000000 --- a/installer/lib/filesystem.sh +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Filesystem creation, mounting and fstab/crypttab generation. -# -# fstab is generated deterministically from the plan rather than scraping the -# live system, so no host state leaks into the installed system. - -declare -g FS_ROOT_SOURCE="" -declare -g FS_EFI_PART="" -declare -g FS_ROOT_PART="" - -filesystem_require_tools() { - require_cmd mkfs.fat mount umount blkid || return 1 -} - -# filesystem_mkfs_efi PARTITION -filesystem_mkfs_efi() { - local part="$1" - run_destructive "create FAT32 EFI filesystem on $part" \ - mkfs.fat -F32 -n EFI "$part" -} - -# filesystem_mount_efi PARTITION ROOT -filesystem_mount_efi() { - local part="$1" root="$2" mp - mp="$(config_get EFI_MOUNT)" - mkdir -p "$root$mp" - run_cmd "mount EFI" mount "$part" "$root$mp" -} - -# filesystem_prepare_root DISK -# Create the root filesystem, applying encryption when configured. -# Sets FS_ROOT_SOURCE to the device that carries the Btrfs filesystem. -filesystem_prepare_root() { - local disk="$1" part="$2" - FS_ROOT_PART="$part" - if [[ "$(config_get ENCRYPTION)" == "none" ]]; then - btrfs_mkfs "$part" || return 1 - FS_ROOT_SOURCE="$part" - else - encryption_format "$part" || return 1 - encryption_open "$part" "$(config_get LUKS_NAME)" || return 1 - local mapper - mapper="$(encryption_mapper_path)" - btrfs_mkfs "$mapper" || return 1 - FS_ROOT_SOURCE="$mapper" - fi - log_info "root filesystem source: $FS_ROOT_SOURCE" -} - -# filesystem_mount_root ROOT -filesystem_mount_root() { - local root="$1" - btrfs_mount_layout "$FS_ROOT_SOURCE" "$root" -} - -# filesystem_source_ref - stable reference for fstab (UUID when unencrypted) -filesystem_source_ref() { - if [[ "$FS_ROOT_SOURCE" == /dev/mapper/* ]]; then - printf '%s' "$FS_ROOT_SOURCE" - else - local uuid - uuid="$(blkid -s UUID -o value "$FS_ROOT_SOURCE" 2>/dev/null)" - if [[ -n "$uuid" ]]; then printf 'UUID=%s' "$uuid"; else printf '%s' "$FS_ROOT_SOURCE"; fi - fi -} - -# filesystem_generate_fstab ROOT -filesystem_generate_fstab() { - local root="$1" - local fstab="$root/etc/fstab" - local opts src - src="$(filesystem_source_ref)" - opts="$(btrfs_mount_opts)" - mkdir -p "$root/etc" - - { - printf '# /etc/fstab: %s\n' "$(config_get DISTRO_NAME)" - printf '# Generated by the installer. Use `findmnt --verify` to check.\n' - printf '#\n' - printf '# \t\t\t\t\t\n' - local efi_uuid - efi_uuid="$(blkid -s UUID -o value "$FS_EFI_PART" 2>/dev/null)" - if [[ -n "$efi_uuid" ]]; then - printf 'UUID=%s\t%s\tvfat\tumask=0077,shortname=winnt\t0\t2\n' "$efi_uuid" "$(config_get EFI_MOUNT)" - fi - printf '%s\t/\tbtrfs\t%s,subvol=@\t0\t1\n' "$src" "$opts" - printf '%s\t/home\tbtrfs\t%s,subvol=@home\t0\t2\n' "$src" "$opts" - printf '%s\t/var\tbtrfs\t%s,subvol=@var\t0\t2\n' "$src" "$opts" - printf '%s\t/.snapshots\tbtrfs\t%s,subvol=@snapshots\t0\t2\n' "$src" "$opts" - printf '%s\t/swap\tbtrfs\t%s,subvol=@swap\t0\t2\n' "$src" "$opts" - printf '/swap/swapfile\tnone\tswap\tdefaults\t0\t0\n' - } >"$fstab" - log_info "wrote $fstab" -} - -# filesystem_generate_crypttab ROOT -filesystem_generate_crypttab() { - local root="$1" - local crypttab="$root/etc/crypttab" - local line - [[ "$(config_get ENCRYPTION)" == "none" ]] && return 0 - line="$(encryption_crypttab_line "$FS_ROOT_PART" "$(config_get LUKS_NAME)")" || { - log_error "could not determine LUKS UUID for crypttab" - return 1 - } - mkdir -p "$root/etc" - { - printf '# /etc/crypttab: unlock the root volume at boot.\n' - printf '# \t\t\t\n' - printf '%s\n' "$line" - } >"$crypttab" - log_info "wrote $crypttab" -} - -# filesystem_verify ROOT - basic post-mount checks -filesystem_verify() { - local root="$1" - [[ -d "$root/etc" ]] || { log_error "$root/etc missing"; return 1; } - findmnt -n "$root" >/dev/null 2>&1 || { log_error "$root is not a mountpoint"; return 1; } - return 0 -} - -# filesystem_unmount_all ROOT - best effort teardown (used on rollback) -filesystem_unmount_all() { - local root="$1" - # Unmount children first, the root last. - local -a mounts=("$(config_get EFI_MOUNT)" "/.snapshots" "/var" "/home" "/swap" "") - local m - for m in "${mounts[@]}"; do - run_cmd "unmount $root$m" umount -R "$root$m" 2>/dev/null || true - done -} diff --git a/installer/lib/hardware.sh b/installer/lib/hardware.sh deleted file mode 100644 index 7cb73d1..0000000 --- a/installer/lib/hardware.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Read-only hardware probing. -# -# Nothing in this file modifies the system: it only reads /proc, /sys and the -# output of read-only inventory tools. Results feed the installation plan and -# the kernel/profile decisions. - -hw_cpu_vendor() { - awk -F': ' '/^vendor_id/{print $2; exit}' /proc/cpuinfo 2>/dev/null -} - -hw_cpu_model() { - awk -F': ' '/^model name/{print $2; exit}' /proc/cpuinfo 2>/dev/null -} - -hw_cpu_cores() { - local n - n="$(nproc --all 2>/dev/null || echo 1)" - printf '%s' "$n" -} - -hw_cpu_threads() { - local n - n="$(grep -c '^processor' /proc/cpuinfo 2>/dev/null || echo 1)" - printf '%s' "$n" -} - -hw_cpu_has() { - grep -qw "$1" /proc/cpuinfo 2>/dev/null -} - -# hw_cpu_virt - print a human readable virtualisation capability summary -hw_cpu_virt() { - local out=() - hw_cpu_has vmx && out+=("Intel VT-x") - hw_cpu_has svm && out+=("AMD-V") - hw_cpu_has avx2 && out+=("AVX2") - hw_cpu_has avx512f && out+=("AVX-512") - hw_cpu_has aes && out+=("AES-NI") - ((${#out[@]})) && printf '%s' "${out[*]}" -} - -hw_mem_total_mib() { - awk '/^MemTotal:/{printf "%d", $2/1024; exit}' /proc/meminfo 2>/dev/null -} - -hw_firmware_mode() { - if [[ -d /sys/firmware/efi ]]; then printf 'UEFI'; else printf 'BIOS'; fi -} - -_is_laptop() { - local p - for p in /sys/class/power_supply/BAT*; do - [[ -e "$p" ]] && return 0 - done - [[ -d /sys/firmware/acpi/tables ]] && \ - grep -qi 'laptop' /sys/class/dmi/id/chassis_type 2>/dev/null - return 1 -} - -# _hw_lspci_filter REGEX - matching lspci lines, if lspci is available -_hw_lspci_filter() { - command -v lspci >/dev/null 2>&1 || return 0 - lspci -nn 2>/dev/null | grep -iE "$1" || true -} - -_hw_lsusb_filter() { - command -v lsusb >/dev/null 2>&1 || return 0 - lsusb 2>/dev/null | grep -iE "$1" || true -} - -hw_gpus() { _hw_lspci_filter 'VGA compatible controller|3D controller|Display controller'; } -hw_network_hw() { _hw_lspci_filter 'Ethernet controller|Network controller|Wireless'; } -hw_bluetooth() { { _hw_lspci_filter 'Bluetooth'; _hw_lsusb_filter 'Bluetooth'; } | sort -u; } -hw_audio() { _hw_lspci_filter 'Audio device'; } -hw_usb() { _hw_lspci_filter 'USB controller'; } -hw_storage_hw() { _hw_lspci_filter 'SATA controller|NVMe|RAID bus controller'; } - -# hw_gpu_vendors - space separated vendor tags, used for driver policy -hw_gpu_vendors() { - local gpus vendors=() - gpus="$(hw_gpus)" - grep -qi 'nvidia' <<<"$gpus" && vendors+=("nvidia") - grep -qi 'amd\|advanced micro devices\|ati technologies' <<<"$gpus" && vendors+=("amd") - grep -qi 'intel' <<<"$gpus" && vendors+=("intel") - printf '%s' "${vendors[*]:-unknown}" -} - -hw_input_devices() { - local count=0 - [[ -r /proc/bus/input/devices ]] && \ - count="$(grep -c '^N: Name=' /proc/bus/input/devices 2>/dev/null)" - printf '%s' "$count" -} - -# hw_report - human readable report for the TUI / hardware screen -hw_report() { - local virt - virt="$(hw_cpu_virt)" - printf 'Firmware: %s\n' "$(hw_firmware_mode)" - printf 'CPU: %s\n' "$(hw_cpu_model)" - printf 'CPU cores: %s threads / %s logical CPUs\n' \ - "$(hw_cpu_threads)" "$(hw_cpu_cores)" - printf 'CPU features: %s\n' "${virt:-none detected}" - printf 'Memory: %s MiB\n' "$(hw_mem_total_mib)" - printf 'Machine type: %s\n' "$(_is_laptop && echo laptop || echo desktop/server)" - printf 'Input devices: %s\n' "$(hw_input_devices)" - printf '\n' - printf 'GPUs:\n%s\n\n' "$(hw_gpus | sed 's/^/ /' | grep . || echo ' (none detected)')" - printf 'Storage controllers:\n%s\n\n' "$(hw_storage_hw | sed 's/^/ /' | grep . || echo ' (none detected)')" - printf 'Network:\n%s\n\n' "$(hw_network_hw | sed 's/^/ /' | grep . || echo ' (none detected)')" - printf 'Bluetooth:\n%s\n\n' "$(hw_bluetooth | sed 's/^/ /' | grep . || echo ' (none detected)')" - printf 'Audio:\n%s\n\n' "$(hw_audio | sed 's/^/ /' | grep . || echo ' (none detected)')" - printf 'USB controllers:\n%s\n' "$(hw_usb | sed 's/^/ /' | grep . || echo ' (none detected)')" -} - -# hw_recommended_kernel_profile - conservative recommendation -hw_recommended_kernel_profile() { - local mem - mem="$(hw_mem_total_mib)" - if [[ -n "$mem" ]] && ((mem < 2048)); then - printf 'safe' - else - printf 'optimized' - fi -} diff --git a/installer/lib/install.sh b/installer/lib/install.sh deleted file mode 100644 index 03e54b9..0000000 --- a/installer/lib/install.sh +++ /dev/null @@ -1,330 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Installation orchestration. -# -# This is the only place that grants destructive authorization, and only after -# the plan has been displayed and explicitly approved. Each stage checks the -# return status of the one before it and stops on failure rather than -# continuing blindly. - -declare -g INSTALL_TARGET_ROOT="" -declare -g INSTALL_FAILED_STAGE="" - -# install_effective_root - the directory the installed system lives in. -# In dry-run mode this is a sandbox so file writes never touch the host. -install_effective_root() { - if config_bool DRY_RUN; then - printf '%s/dry-run-root' "${STATE_DIR:-/tmp/ai-installer}" - else - printf '%s' "$(config_get INSTALL_ROOT)" - fi -} - -install_require_root() { - if config_bool DRY_RUN; then return 0; fi - if [[ "$(id -u)" -ne 0 ]]; then - log_error "the installer must run as root" - return 1 - fi - return 0 -} - -# install_preflight - non-destructive checks before anything is touched -install_preflight() { - log_section "preflight" - install_require_root || return 1 - if ! config_bool DRY_RUN && [[ ! -d /sys/firmware/efi ]]; then - log_error "system was not booted in UEFI mode; v0.1 supports UEFI only" - return 1 - fi - local problems - problems="$(validate_config)" - if [[ -n "$problems" ]]; then - log_error "configuration is incomplete:" - while IFS= read -r problems; do log_error " $problems"; done <<<"$problems" - return 1 - fi - partitions_require_tools || return 1 - filesystem_require_tools || return 1 - btrfs_require_tools || return 1 - if [[ "$(config_get ENCRYPTION)" != "none" ]]; then - encryption_require_tools || return 1 - fi - if [[ -z "$LUKS_PASSPHRASE" && "$(config_get ENCRYPTION)" != "none" ]]; then - log_error "encryption selected but no passphrase configured" - return 1 - fi - return 0 -} - -# install_chroot_mount ROOT / install_chroot_umount ROOT -install_chroot_mount() { - local root="$1" - run_cmd "mount proc" mount -t proc proc "$root/proc" || return 1 - run_cmd "mount sysfs" mount --rbind /sys "$root/sys" || return 1 - run_cmd "mount devtmpfs" mount --rbind /dev "$root/dev" || return 1 - run_cmd "mount devpts" mount --make-rslave "$root/dev" 2>/dev/null || true - [[ -d "$root/run" ]] && run_cmd "mount tmpfs on /run" mount -t tmpfs tmpfs "$root/run" || true - return 0 -} - -install_chroot_umount() { - local root="$1" - run_cmd "unmount $root/proc" umount -l "$root/proc" 2>/dev/null || true - run_cmd "unmount $root/sys" umount -l "$root/sys" 2>/dev/null || true - run_cmd "unmount $root/dev" umount -l "$root/dev" 2>/dev/null || true -} - -# install_stage_storage - create partitions, filesystems and mount the target -install_stage_storage() { - local disk root - disk="$(config_get TARGET_DISK)" - root="$INSTALL_TARGET_ROOT" - log_section "storage: $disk" - - if config_bool DRY_RUN; then - log_info "[dry-run] would partition and format $disk at $root" - mkdir -p "$root" - return 0 - fi - - partitions_wipe "$disk" || return 1 - partitions_create_gpt "$disk" || return 1 - partitions_verify "$disk" || return 1 - FS_EFI_PART="$EFI_PART" - - filesystem_mkfs_efi "$EFI_PART" || return 1 - filesystem_prepare_root "$disk" "$ROOT_PART" || return 1 - # Create the subvolume layout and mount the root; mounting the ESP afterwards - # avoids covering the ESP mount with the root filesystem. - btrfs_create_layout "$FS_ROOT_SOURCE" "$root" || return 1 - filesystem_mount_efi "$EFI_PART" "$root" || return 1 - btrfs_create_swapfile "$root" || return 1 - # NOTE: /etc/fstab and /etc/crypttab are generated after the stage3 is - # extracted (install_stage_fstab); generating them here would be undone by - # the stage3 tarball, which ships its own /etc/fstab. - return 0 -} - -# install_stage_fstab - write fstab, crypttab and required runtime directories. -# Runs after the stage3 has been extracted so nothing overwrites these files. -install_stage_fstab() { - local root="$INSTALL_TARGET_ROOT" - log_section "fstab / crypttab" - if config_bool DRY_RUN; then - log_info "[dry-run] would write fstab and crypttab into $root" - return 0 - fi - filesystem_generate_fstab "$root" || return 1 - filesystem_generate_crypttab "$root" || return 1 - # Some stage3 media omit /var/tmp; systemd's kernel-install needs it. - mkdir -p "$root/var/tmp" "$root/tmp" "$root/root" "$root/home" - chmod 1777 "$root/var/tmp" "$root/tmp" 2>/dev/null || true - chmod 0700 "$root/root" 2>/dev/null || true - return 0 -} - -# install_stage_base - extract the Gentoo systemd stage3 -install_stage_base() { - local root="$INSTALL_TARGET_ROOT" tarball - log_section "base system (stage3)" - mkdir -p "$root" "${STATE_DIR:-/tmp/ai-installer}" - tarball="${STATE_DIR:-/tmp/ai-installer}/stage3-systemd.tar.xz" - if config_bool DRY_RUN; then - log_info "[dry-run] would fetch stage3 and extract into $root" - return 0 - fi - portage_fetch_stage3 "$tarball" || return 1 - portage_extract_stage3 "$root" "$tarball" || return 1 - return 0 -} - -# install_stage_portage - configure Portage and sync -install_stage_portage() { - local root="$INSTALL_TARGET_ROOT" - log_section "portage configuration" - if config_bool DRY_RUN; then - log_info "[dry-run] would write Portage config and sync" - return 0 - fi - portage_write_make_conf "$root" || return 1 - portage_write_repos_conf "$root" || return 1 - portage_write_binrepos "$root" || return 1 - portage_write_package_files "$root" || return 1 - cp -L /etc/resolv.conf "$root/etc/resolv.conf" 2>/dev/null || true - install_chroot_mount "$root" || return 1 - portage_init_machine_id "$root" || log_warn "could not initialise machine-id" - portage_sync "$root" || { install_chroot_umount "$root"; return 1; } - portage_verification_setup "$root" || log_warn "getuto failed; binary package verification may fail" - install_chroot_umount "$root" - # Select the profile only after the tree exists, so the symlink is never - # dangling while Portage runs. - portage_select_profile "$root" || return 1 - return 0 -} - -# install_stage_packages - base packages beyond the stage3 -install_stage_packages() { - local root="$INSTALL_TARGET_ROOT" - local -a packages=() - log_section "base packages" - mapfile -t packages < <(portage_base_packages) - install_chroot_mount "$root" || return 1 - portage_emerge "$root" "${packages[@]}" || { install_chroot_umount "$root"; return 1; } - install_chroot_umount "$root" - return 0 -} - -# install_stage_kernel -install_stage_kernel() { - local root="$INSTALL_TARGET_ROOT" - log_section "kernel" - kernel_write_profile "$root" || return 1 - boot_write_install_conf "$root" || return 1 - boot_write_dracut_conf "$root" || return 1 - kernel_write_cmdline "$root" || return 1 - install_chroot_mount "$root" || return 1 - kernel_install "$root" || { install_chroot_umount "$root"; return 1; } - install_chroot_umount "$root" - return 0 -} - -# install_stage_boot -install_stage_boot() { - local root="$INSTALL_TARGET_ROOT" - log_section "bootloader" - install_chroot_mount "$root" || return 1 - boot_install "$root" || log_warn "bootctl install failed; will rely on the EFI fallback path" - boot_generate_uki "$root" || log_warn "kernel-install add-all reported an issue" - install_chroot_umount "$root" - boot_write_loader_conf "$root" || return 1 - boot_install_fallback "$root" || log_warn "EFI fallback bootloader not installed" - boot_random_seed "$root" || true - boot_verify "$root" || return 1 - return 0 -} - -# install_stage_users -install_stage_users() { - local root="$INSTALL_TARGET_ROOT" - log_section "users" - install_chroot_mount "$root" || return 1 - users_create "$root" || { install_chroot_umount "$root"; return 1; } - users_configure_sudo "$root" || { install_chroot_umount "$root"; return 1; } - install_chroot_umount "$root" - return 0 -} - -# install_stage_services - locale, timezone, keymap, systemd services -install_stage_services() { - local root="$INSTALL_TARGET_ROOT" tz locale keymap - log_section "system services" - tz="$(config_get TIMEZONE)" - locale="$(config_get LOCALE)" - keymap="$(config_get KEYMAP)" - - network_configure_target "$root" || return 1 - mkdir -p "$root/etc" - { - printf 'KEYMAP=%s\n' "$keymap" - } >"$root/etc/vconsole.conf" - ln -sf "/usr/share/zoneinfo/$tz" "$root/etc/localtime" - { - printf 'LANG=%s\n' "$locale" - } >"$root/etc/locale.conf" - portage_write_locale_gen "$root" "$locale" - - install_chroot_mount "$root" || return 1 - portage_chroot "$root" locale-gen || log_warn "locale-gen failed (continuing)" - local svc - local -a services=() - mapfile -t services < <(network_target_services) - mapfile -t -O "${#services[@]}" services < <(desktop_services) - printf '%s\n' "${services[@]}" | sort -u >"$root/etc/.phoebus-services" - while IFS= read -r svc; do - [[ -z "$svc" ]] && continue - portage_chroot "$root" systemctl enable "$svc" || log_warn "could not enable $svc" - done <"$root/etc/.phoebus-services" - rm -f "$root/etc/.phoebus-services" - install_chroot_umount "$root" - return 0 -} - -# install_stage_desktop -install_stage_desktop() { - local root="$INSTALL_TARGET_ROOT" profile - profile="$(config_get DESKTOP_PROFILE)" - log_section "desktop: $profile" - [[ "$profile" == "none" ]] && return 0 - install_chroot_mount "$root" || return 1 - desktop_install "$root" || { install_chroot_umount "$root"; return 1; } - desktop_configure_flatpak "$root" || true - install_chroot_umount "$root" - return 0 -} - -# install_export_logs ROOT - copy the installer log into the target so a -# failed installation can be diagnosed after reboot. -install_export_logs() { - local root="$1" dest - dest="$root/var/log/ai-installer" - [[ -r "${PHOEBUS_LOG_FILE:-}" ]] || return 0 - mkdir -p "$dest" 2>/dev/null || return 0 - cp -f "$PHOEBUS_LOG_FILE" "$dest/install.log" 2>/dev/null || true -} - -# install_stage_finalize -install_stage_finalize() { - local root="$INSTALL_TARGET_ROOT" - log_section "finalize" - if ! config_bool DRY_RUN; then - install_export_logs "$root" - install_chroot_umount "$root" - filesystem_unmount_all "$root" - if [[ "$(config_get ENCRYPTION)" != "none" ]]; then - encryption_close "$(config_get LUKS_NAME)" || log_warn "could not close LUKS device" - fi - fi - log_info "installation finished" - return 0 -} - -# install_run - execute the staged installation, stopping on first failure -install_run() { - INSTALL_TARGET_ROOT="$(install_effective_root)" - INSTALL_FAILED_STAGE="" - mkdir -p "$INSTALL_TARGET_ROOT" 2>/dev/null || true - - install_preflight || { INSTALL_FAILED_STAGE="preflight"; return 1; } - - local stage rc - for stage in "${PLAN_STEPS[@]}"; do - rc=0 - case "$stage" in - storage_prepare) install_stage_storage || rc=1 ;; - stage_install) install_stage_base || rc=1 ;; - fstab_generate) install_stage_fstab || rc=1 ;; - portage_configure) install_stage_portage || rc=1 ;; - packages_base) install_stage_packages || rc=1 ;; - kernel_install) install_stage_kernel || rc=1 ;; - boot_install) install_stage_boot || rc=1 ;; - users_configure) install_stage_users || rc=1 ;; - services_configure) install_stage_services || rc=1 ;; - desktop_install) install_stage_desktop || rc=1 ;; - finalize) install_stage_finalize || rc=1 ;; - *) log_warn "unknown stage: $stage" ;; - esac - if ((rc != 0)); then - INSTALL_FAILED_STAGE="$stage" - log_error "stage failed: $stage" - if ! config_bool DRY_RUN; then - install_export_logs "$INSTALL_TARGET_ROOT" - install_chroot_umount "$INSTALL_TARGET_ROOT" - fi - return 1 - fi - log_info "stage complete: $stage" - done - return 0 -} diff --git a/installer/lib/kernel.sh b/installer/lib/kernel.sh deleted file mode 100644 index 0d665e4..0000000 --- a/installer/lib/kernel.sh +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Kernel selection and configuration. -# -# Policy: compile an "optimized but conservative" kernel. We start from the -# Gentoo distribution kernel (sys-kernel/gentoo-kernel), which is a stable, -# well-tested configuration, and apply a small, safe set of profile fragments. -# We never generate a minimal config that only boots the installer's hardware. - -kernel_profile_file() { - printf '%s/etc/kernel/config.d/00-phoebus-profile.config' "$1" -} - -# kernel_modules_for_hardware - extra kernel packages suggested by hardware -kernel_extra_packages() { - printf '%s\n' sys-kernel/linux-firmware - if hw_cpu_has vmx; then - printf '%s\n' sys-firmware/intel-microcode - fi - if hw_cpu_has svm; then - printf '%s\n' sys-firmware/amd-ucode - fi -} - -# kernel_select_package - final kernel package respecting the profile -kernel_select_package() { - local pkg profile - pkg="$(config_get KERNEL_PACKAGE)" - profile="$(config_get KERNEL_PROFILE)" - case "$profile" in - safe) - # Safe profile prefers the prebuilt distribution kernel. - printf '%s' "sys-kernel/gentoo-kernel-bin" ;; - optimized) - printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;; - aggressive) - # Aggressive still uses the distribution sources but may take a - # locally tuned savedconfig fragment. - printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;; - *) - printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;; - esac -} - -# kernel_write_profile ROOT - safe config fragments (never minimal) -kernel_write_profile() { - local root="$1" profile file - profile="$(config_get KERNEL_PROFILE)" - file="$(kernel_profile_file "$root")" - mkdir -p "$(dirname "$file")" - { - printf '# %s kernel profile: %s\n' "$(config_get DISTRO_NAME)" "$profile" - printf '# Applied on top of the Gentoo distribution kernel configuration.\n' - printf '# The base configuration is intentionally kept: it supports common\n' - printf '# peripherals the user may attach later.\n' - printf '\n' - printf '# Storage / modern filesystems and encryption\n' - printf 'CONFIG_BTRFS_FS=y\n' - printf 'CONFIG_BTRFS_FS_POSIX_ACL=y\n' - printf 'CONFIG_DM_CRYPT=y\n' - printf 'CONFIG_DM_INTEGRITY=y\n' - printf 'CONFIG_NVME_CORE=y\n' - printf 'CONFIG_BLK_DEV_NVME=y\n' - printf '\n' - printf '# Input / USB / common buses\n' - printf 'CONFIG_HID_GENERIC=y\n' - printf 'CONFIG_USB_HID=y\n' - printf 'CONFIG_USB_XHCI_HCD=y\n' - printf '\n' - printf '# systemd / containers / virtualisation guests\n' - printf 'CONFIG_CGROUPS=y\n' - printf 'CONFIG_NAMESPACES=y\n' - printf 'CONFIG_VIRTIO=y\n' - printf 'CONFIG_VIRTIO_PCI=y\n' - printf 'CONFIG_VIRTIO_BLK=y\n' - printf 'CONFIG_VIRTIO_NET=y\n' - printf '\n' - printf '# Compression used by Btrfs\n' - printf 'CONFIG_ZSTD_COMPRESS=y\n' - printf 'CONFIG_ZSTD_DECOMPRESS=y\n' - } >"$file" - log_info "wrote kernel profile fragment $file" -} - -# kernel_write_cmdline ROOT - kernel command line for UKI/systemd-boot -kernel_write_cmdline() { - local root="$1" cmdline="" enc name uuid - enc="$(config_get ENCRYPTION)" - name="$(config_get LUKS_NAME)" - if [[ "$enc" != "none" ]]; then - uuid="$(blkid -s UUID -o value "$FS_ROOT_PART" 2>/dev/null)" - if [[ -z "$uuid" ]]; then - if config_bool DRY_RUN; then - uuid="" - else - log_error "cannot determine LUKS UUID for kernel command line" - return 1 - fi - fi - # rd.luks.name== makes dracut/systemd create the mapper under - # the configured name; rd.luks.uuid alone would produce luks- and the - # root= below would not exist. - cmdline+="rd.luks.name=$uuid=$name " - cmdline+="root=/dev/mapper/$name " - else - cmdline+="root=$(filesystem_source_ref) " - fi - cmdline+="rootfstype=btrfs rootflags=subvol=@ rw quiet" - local console - console="$(config_get KERNEL_CONSOLE)" - [[ -n "$console" ]] && cmdline+=" $console" - mkdir -p "$root/etc/kernel" - printf '%s\n' "$cmdline" >"$root/etc/kernel/cmdline" - log_info "wrote /etc/kernel/cmdline: $cmdline" -} - -# kernel_install ROOT - emerge the kernel and firmware -kernel_install() { - local root="$1" pkg - pkg="$(kernel_select_package)" - local -a packages=("$pkg") - mapfile -t -O "${#packages[@]}" packages < <(kernel_extra_packages) - log_info "installing kernel packages: ${packages[*]}" - portage_emerge "$root" "${packages[@]}" -} - -# kernel_update ROOT - rebuild the distribution kernel via emerge @module-rebuild -kernel_update() { - local root="$1" - portage_chroot "$root" emerge --ask=n --quiet-build=y @module-rebuild -} - -# kernel_available_list ROOT - kernels present in the ESP -kernel_available_list() { - local root="$1" esp - esp="$root$(config_get EFI_MOUNT)" - find "$esp" -maxdepth 4 -name 'vmlinuz*' -o -name '*.efi' 2>/dev/null | sed "s#^$root##" -} diff --git a/installer/lib/logging.sh b/installer/lib/logging.sh deleted file mode 100644 index fe3dcd3..0000000 --- a/installer/lib/logging.sh +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Installer logging and command execution. -# -# Every operation performed by the deterministic backend goes through run_cmd -# (or run_cmd_capture), which records the command, its output and its exit -# status. This makes failures diagnosable and keeps destructive behaviour -# auditable. -# -# Secrets are scrubbed from all log output. - -declare -g PHOEBUS_LOG_FILE="${PHOEBUS_LOG_FILE:-}" -declare -g PHOEBUS_LOG_ECHO="${PHOEBUS_LOG_ECHO:-no}" -declare -ga SECRET_VALUES=() - -# secret_register VALUE - remember a secret so it is never written to logs -secret_register() { - [[ -n "${1-}" ]] && SECRET_VALUES+=("$1") -} - -# redact_scrub TEXT - replace every known secret with -redact_scrub() { - local text="$1" secret - for secret in "${SECRET_VALUES[@]}"; do - [[ -n "$secret" ]] && text="${text//"$secret"/}" - done - printf '%s' "$text" -} - -log_init() { - local dir - dir="${LOG_DIR:-/var/log/ai-installer}" - if ! mkdir -p "$dir" 2>/dev/null || [[ ! -w "$dir" ]]; then - dir="${STATE_DIR:-/tmp/ai-installer}/logs" - mkdir -p "$dir" 2>/dev/null || true - fi - PHOEBUS_LOG_FILE="${PHOEBUS_LOG_FILE:-$dir/install.log}" - : >"$PHOEBUS_LOG_FILE" 2>/dev/null || PHOEBUS_LOG_FILE=/dev/null - log_line INFO "=== ${DISTRO_NAME:-Phoebus OS} installer started ===" - log_line INFO "log file: $PHOEBUS_LOG_FILE" -} - -log_line() { - local level="$1" message="${2-}" - local ts - ts="$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)" - message="$(redact_scrub "$message")" - printf '%s [%s] %s\n' "$ts" "$level" "$message" >>"$PHOEBUS_LOG_FILE" 2>/dev/null || true - if [[ "$PHOEBUS_LOG_ECHO" == "yes" ]]; then - printf '%s [%s] %s\n' "$ts" "$level" "$message" >&2 - fi -} - -log_debug() { log_line DEBUG "$@"; } -log_info() { log_line INFO "$@"; } -log_warn() { log_line WARN "$@"; } -log_error() { log_line ERROR "$@"; } -log_section() { log_line INFO "--- $* ---"; } - -# _cmd_to_string ARGS... - printable, redacted representation of a command -_cmd_to_string() { - local out="" arg - for arg in "$@"; do - out+="$(printf '%q' "$arg") " - done - redact_scrub "${out% }" -} - -# run_cmd DESCRIPTION ARGS... -# Execute a command, streaming stdout/stderr to the log. Honours DRY_RUN. -run_cmd() { - local desc="$1"; shift - local printable status - printable="$(_cmd_to_string "$@")" - if config_bool DRY_RUN; then - log_line INFO "[dry-run] $desc :: $printable" - return 0 - fi - log_line INFO "$desc :: $printable" - "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 - status=$? - log_line INFO "$desc :: exit status $status" - return $status -} - -# run_cmd_capture DESCRIPTION ARGS... -# Like run_cmd but stdout is stored in RUN_OUTPUT and not streamed. stderr -# still goes to the log. Never logs the captured stdout (may contain secrets). -run_cmd_capture() { - local desc="$1"; shift - local printable status - RUN_OUTPUT="" - printable="$(_cmd_to_string "$@")" - if config_bool DRY_RUN; then - log_line INFO "[dry-run] $desc (capture) :: $printable" - return 0 - fi - log_line DEBUG "$desc (capture) :: $printable" - RUN_OUTPUT="$("$@" 2>>"$PHOEBUS_LOG_FILE")" - status=$? - log_line DEBUG "$desc :: exit status $status" - return $status -} - -# run_cmd_quiet DESCRIPTION ARGS... - output fully suppressed -run_cmd_quiet() { - local desc="$1"; shift - local printable status - printable="$(_cmd_to_string "$@")" - if config_bool DRY_RUN; then - log_line INFO "[dry-run] $desc :: $printable" - return 0 - fi - log_line DEBUG "$desc (quiet) :: $printable" - "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 - status=$? - log_line DEBUG "$desc :: exit status $status" - return $status -} - -# require_cmd NAME... - fail fast when a required tool is unavailable -require_cmd() { - local missing=() name - for name in "$@"; do - command -v "$name" >/dev/null 2>&1 || missing+=("$name") - done - if ((${#missing[@]})); then - log_error "missing required command(s): ${missing[*]}" - return 1 - fi - return 0 -} - -# log_tail [N] - last N lines of the log (for the TUI) -log_tail() { - local n="${1:-40}" - tail -n "$n" "$PHOEBUS_LOG_FILE" 2>/dev/null -} diff --git a/installer/lib/network.sh b/installer/lib/network.sh deleted file mode 100644 index b6cca78..0000000 --- a/installer/lib/network.sh +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Networking for the live environment and for the installed system. -# -# In the live environment we drive NetworkManager (present in the Gentoo -# LiveGUI reference) because it works for both wired and wireless. The installed -# system also uses NetworkManager, which matches the desktop profile. - -WIFI_PASSPHRASE="" - -network_interfaces() { - local iface - for iface in /sys/class/net/*; do - iface="${iface##*/}" - [[ "$iface" == "lo" ]] && continue - printf '%s\n' "$iface" - done -} - -network_is_wireless() { - local iface="$1" - [[ -d "/sys/class/net/$iface/wireless" ]] || \ - [[ -d "/sys/class/net/$iface/phy80211" ]] -} - -network_interface_state() { - cat "/sys/class/net/$1/operstate" 2>/dev/null || printf 'unknown' -} - -network_online() { - command -v ip >/dev/null 2>&1 || return 1 - ip route show default 2>/dev/null | grep -q 'default' && return 0 - if command -v ping >/dev/null 2>&1; then - ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 && return 0 - fi - return 1 -} - -network_status_text() { - local iface - printf 'Connectivity: %s\n\n' "$(network_online && echo online || echo offline)" - for iface in $(network_interfaces); do - local kind state - kind="$(network_is_wireless "$iface" && echo wireless || echo wired)" - state="$(network_interface_state "$iface")" - printf ' %-12s %-8s %s\n' "$iface" "$kind" "$state" - done -} - -# network_live_start - best effort start of the live network manager -network_live_start() { - if command -v rc-service >/dev/null 2>&1; then - run_cmd "start NetworkManager (OpenRC)" rc-service NetworkManager start 2>/dev/null || true - fi - if command -v nmcli >/dev/null 2>&1; then - run_cmd "ensure NetworkManager running" nmcli general status >/dev/null 2>&1 || true - fi - if command -v rfkill >/dev/null 2>&1; then - run_cmd "unblock wifi" rfkill unblock wifi 2>/dev/null || true - fi -} - -# network_connect_wifi SSID PASSPHRASE - live environment helper -network_connect_wifi() { - local ssid="$1" pass="$2" - command -v nmcli >/dev/null 2>&1 || { log_error "nmcli not available"; return 1; } - secret_register "$pass" - if [[ -n "$pass" ]]; then - run_cmd "connect to wifi '$ssid'" nmcli device wifi connect "$ssid" password "$pass" - else - run_cmd "connect to wifi '$ssid'" nmcli device wifi connect "$ssid" - fi -} - -# network_wifi_scan - print "SSID SIGNAL SECURITY" lines -network_wifi_scan() { - command -v nmcli >/dev/null 2>&1 || return 1 - nmcli -t -f SSID,SIGNAL,SECURITY device wifi list 2>/dev/null | \ - awk -F: 'NF && $1!=""{printf "%-32s %3s%% %s\n", $1, $2, $3}' -} - -# network_configure_target ROOT -# Write the target hostname and enable the networking services. Service -# enablement itself happens inside the chroot during install. -network_configure_target() { - local root="$1" hostname - hostname="$(config_get HOSTNAME)" - mkdir -p "$root/etc" - printf '%s\n' "$hostname" >"$root/etc/hostname" - { - printf '127.0.0.1\tlocalhost\n' - printf '::1\t\tlocalhost\n' - printf '127.0.1.1\t%s\n' "$hostname" - } >"$root/etc/hosts" - log_info "configured hostname '$hostname' in target" -} - -# network_target_service_names - services to enable in the installed system -network_target_services() { - printf '%s\n' NetworkManager systemd-resolved -} diff --git a/installer/lib/opencode.sh b/installer/lib/opencode.sh deleted file mode 100644 index 865af10..0000000 --- a/installer/lib/opencode.sh +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Reproducible OpenCode provisioning. -# -# The vendor installer (curl | sh) is never used. We fetch a pinned release -# tarball from the official GitHub release and verify its SHA-256 against the -# local manifest before extracting it. The binary is never executed during -# verification. - -opencode_manifest_file() { - printf '%s/config/opencode.manifest' "$PHOEBUS_ROOT" -} - -opencode_manifest_get() { - local arch="$1" key="$2" file out - file="$(opencode_manifest_file)" - [[ -r "$file" ]] || return 1 - out="$(awk -F= -v a="$arch" -v k="$key" '$1==a"."k{sub(/^[^=]*=/,""); print; exit}' "$file")" - [[ -n "$out" ]] || return 1 - printf '%s' "$out" -} - -opencode_version_manifest() { - local file - file="$(opencode_manifest_file)" - awk -F= '$1=="VERSION"{print $2; exit}' "$file" 2>/dev/null -} - -opencode_arch() { - case "$(uname -m)" in - x86_64|amd64) printf 'x86_64' ;; - aarch64|arm64) printf 'aarch64' ;; - *) printf 'unsupported' ;; - esac -} - -# opencode_bin_dir - where the verified binary lives -opencode_bin_dir() { - if [[ -n "${PHOEBUS_OPENCODE_DIR:-}" ]]; then - printf '%s' "$PHOEBUS_OPENCODE_DIR" - elif [[ -w /opt ]]; then - printf '/opt/phoebus/opencode' - else - printf '%s/opencode' "${STATE_DIR:-/tmp/ai-installer}" - fi -} - -# opencode_detect - print the path to a usable opencode binary, if any -opencode_detect() { - local candidate - if command -v opencode >/dev/null 2>&1; then - command -v opencode - return 0 - fi - for candidate in "$(opencode_bin_dir)/opencode" /usr/local/bin/opencode; do - [[ -x "$candidate" ]] && { printf '%s' "$candidate"; return 0; } - done - return 1 -} - -opencode_available() { opencode_detect >/dev/null 2>&1; } - -# opencode_checksum_ok FILE EXPECTED - false for placeholders or mismatches -opencode_checksum_ok() { - local file="$1" expected="$2" got - [[ -n "$expected" ]] || return 1 - [[ "$expected" =~ ^0+$ ]] && return 1 - got="$(sha256sum "$file" | awk '{print $1}')" - [[ "$got" == "$expected" ]] -} - -# opencode_bootstrap [DESTDIR] - download, verify and extract a pinned release -opencode_bootstrap() { - local dest="${1:-$(opencode_bin_dir)}" - local arch url sha binary tmp - arch="$(opencode_arch)" - if [[ "$arch" == "unsupported" ]]; then - log_error "OpenCode: unsupported architecture $(uname -m)" - return 1 - fi - url="$(opencode_manifest_get "$arch" url)" - sha="$(opencode_manifest_get "$arch" sha256)" - binary="$(opencode_manifest_get "$arch" binary)" - binary="${binary:-opencode}" - - if [[ -z "$url" || -z "$sha" ]]; then - log_error "OpenCode: no pinned manifest entry for $arch" - return 1 - fi - if [[ "$sha" =~ ^0+$ ]]; then - log_error "OpenCode: manifest has a placeholder checksum for $arch; refusing" - return 1 - fi - require_cmd curl sha256sum tar || return 1 - - mkdir -p "$dest" || return 1 - tmp="$(mktemp "${TMPDIR:-/tmp}/opencode.XXXXXX.tar.gz")" || return 1 - # shellcheck disable=SC2064 - trap "rm -f '$tmp'" RETURN - log_info "OpenCode: fetching $url" - if ! run_cmd "download OpenCode" curl -fL --retry 3 -o "$tmp" "$url"; then - return 1 - fi - if ! opencode_checksum_ok "$tmp" "$sha"; then - log_error "OpenCode: SHA-256 verification FAILED; discarding download" - rm -f "$tmp" - return 1 - fi - log_info "OpenCode: checksum verified" - run_cmd "extract OpenCode" tar -xzf "$tmp" -C "$dest" || return 1 - [[ -f "$dest/$binary" ]] || { log_error "OpenCode: expected binary '$binary' not found"; return 1; } - chmod 0755 "$dest/$binary" - ln -sf "$dest/$binary" "$dest/opencode" 2>/dev/null || true - log_info "OpenCode installed at $dest/$binary ($(opencode_version_manifest))" - return 0 -} - -# opencode_ensure - ensure a binary is present, bootstrapping if needed -opencode_ensure() { - opencode_available && return 0 - log_info "OpenCode not found; bootstrapping pinned release" - opencode_bootstrap -} - -# opencode_print_version BIN -opencode_print_version() { - local bin="$1" - "$bin" --version 2>/dev/null | head -n1 -} - -# opencode_ai_config_path - where the installer keeps AI provider config -opencode_ai_config_path() { - printf '%s/ai/opencode.json' "${STATE_DIR:-/tmp/ai-installer}" -} - -# opencode_write_config - write provider/model config (never secrets) -opencode_write_config() { - local path dir provider model endpoint - path="$(opencode_ai_config_path)" - dir="$(dirname "$path")" - mkdir -p "$dir" - provider="$(config_get AI_PROVIDER)" - model="$(config_get AI_MODEL)" - endpoint="$(config_get AI_ENDPOINT)" - { - printf '{\n' - printf ' "$schema": "https://opencode.ai/config.json"\n' - if [[ -n "$provider" ]]; then printf ' ,"provider": "%s"\n' "$provider"; fi - if [[ -n "$model" ]]; then printf ' ,"model": "%s"\n' "$model"; fi - if [[ -n "$endpoint" ]]; then printf ' ,"baseURL": "%s"\n' "$endpoint"; fi - printf '}\n' - } >"$path" - chmod 0600 "$path" - log_info "wrote OpenCode config to $path (credentials are never stored here)" -} diff --git a/installer/lib/partitions.sh b/installer/lib/partitions.sh deleted file mode 100644 index 8b824b3..0000000 --- a/installer/lib/partitions.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# GPT partition creation for the installation target. -# -# Every function here is destructive and must be invoked through -# run_destructive, which enforces prior authorization. - -# partitions_require_tools -partitions_require_tools() { - require_cmd sgdisk partprobe blkid wipefs || return 1 -} - -# partitions_wipe DISK - zap all existing partition signatures -partitions_wipe() { - local disk="$1" - run_destructive "wipe partition signatures on $disk" wipefs -a "$disk" || return 1 - run_destructive "zap GPT/MBR on $disk" sgdisk --zap-all "$disk" -} - -# partitions_create_gpt DISK - EFI + root (LUKS or plain btrfs) -partitions_create_gpt() { - local disk="$1" - local efi_mib root_type=8309 - efi_mib="$(config_get EFI_SIZE_MIB)" - [[ "$efi_mib" =~ ^[0-9]+$ ]] || efi_mib=1024 - if [[ "$(config_get ENCRYPTION)" == "none" ]]; then - root_type=8300 - fi - - run_destructive "create GPT on $disk" sgdisk --set-alignment=2048 \ - --new=1:0:+${efi_mib}M --typecode=1:ef00 --change-name=1:EFI \ - --new=2:0:0 --typecode=2:${root_type} --change-name=2:phoebus-root \ - "$disk" || return 1 - run_destructive "re-read partition table on $disk" partprobe "$disk" - command -v udevadm >/dev/null 2>&1 && run_cmd "settle udev" udevadm settle -} - -# partitions_named DISK - first EFI and root partition paths via blkid -partitions_named() { - local disk="$1" - EFI_PART="" ROOT_PART="" - # Prefer explicit GPT names when available. - if command -v blkid >/dev/null 2>&1; then - local dev label - while IFS= read -r dev; do - label="$(blkid -s PARTLABEL -o value "$dev" 2>/dev/null)" - case "$label" in - EFI) EFI_PART="$dev" ;; - phoebus-root) ROOT_PART="$dev" ;; - esac - done < <(disk_partitions "$disk") - fi - # Fallback by order. - local -a parts=() - mapfile -t parts < <(disk_partitions "$disk") - [[ -z "$EFI_PART" && ${#parts[@]} -ge 1 ]] && EFI_PART="${parts[0]}" - [[ -z "$ROOT_PART" && ${#parts[@]} -ge 2 ]] && ROOT_PART="${parts[1]}" - [[ -n "$EFI_PART" && -n "$ROOT_PART" ]] -} - -# partitions_verify DISK - sanity check after creation -partitions_verify() { - local disk="$1" - partitions_named "$disk" || { log_error "could not identify created partitions on $disk"; return 1; } - [[ -b "$EFI_PART" && -b "$ROOT_PART" ]] || { log_error "partition devices missing"; return 1; } - log_info "partitions: EFI=$EFI_PART root=$ROOT_PART" - return 0 -} diff --git a/installer/lib/pkgpolicy.sh b/installer/lib/pkgpolicy.sh deleted file mode 100644 index dc1f67b..0000000 --- a/installer/lib/pkgpolicy.sh +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Package compilation policy. -# -# The rule is deliberately deterministic: -# -# compile when compilation is cheap OR gives a meaningful benefit; -# use a binary when compilation is expensive AND the benefit is negligible. -# -# Decisions are driven by a small curated table plus optional historical -# compile-time data. An LLM is never consulted to guess performance. -# -# Historical data format (tab separated), one package per line: -# category/packagesecondsupdates-per-year -# Overrides the built-in estimate. - -declare -gA PKGPOLICY_COMPILE_SECONDS=( - [app-editors/vim]=45 - [app-misc/tmux]=20 - [app-shells/zsh]=60 - [dev-lang/python]=900 - [dev-lang/rust]=3600 - [dev-libs/glib]=120 - [dev-util/cmake]=300 - [dev-vcs/git]=120 - [media-video/ffmpeg]=900 - [net-misc/curl]=90 - [sys-apps/busybox]=60 - [sys-apps/coreutils]=120 - [sys-apps/systemd]=420 - [sys-devel/gcc]=3600 - [sys-kernel/gentoo-kernel]=1800 - [sys-kernel/gentoo-sources]=120 - [sys-libs/glibc]=900 - [www-client/firefox]=4200 - [www-client/chromium]=7200 - [app-office/libreoffice]=5400 - [dev-qt/qtbase]=900 - [kde-plasma/plasma-desktop]=600 - [net-im/discord-bin]=0 - [games-util/steam-launcher]=0 -) - -# Packages where a binary package is strongly preferred (huge + frequent -# updates + negligible local optimisation benefit + runtime CPU dispatch). -declare -gA PKGPOLICY_BINARY_PREFERRED=( - [www-client/firefox]=1 - [www-client/chromium]=1 - [app-office/libreoffice]=1 - [mail-client/thunderbird]=1 - [dev-lang/rust]=1 - [dev-lang/llvm]=1 - [dev-qt/qtwebengine]=1 - [sys-devel/gcc]=1 - [sys-libs/glibc]=1 - [net-im/discord-bin]=1 - [games-util/steam-launcher]=1 -) - -# Packages that genuinely benefit from local optimisation or USE customisation. -declare -gA PKGPOLICY_SOURCE_PREFERRED=( - [sys-kernel/gentoo-kernel]=1 - [sys-kernel/gentoo-sources]=1 - [sys-apps/systemd]=1 - [app-shells/zsh]=1 - [sys-apps/busybox]=1 - [sys-fs/btrfs-progs]=1 - [sys-fs/cryptsetup]=1 -) - -PKGPOLICY_HISTORY_FILE="" - -pkgpolicy_history_file() { - printf '%s' "${PKGPOLICY_HISTORY_FILE:-${STATE_DIR:-/tmp/ai-installer}/compile-times.tsv}" -} - -pkgpolicy_compile_seconds() { - local pkg="$1" hist line - hist="$(pkgpolicy_history_file)" - if [[ -r "$hist" ]]; then - line="$(awk -F'\t' -v p="$pkg" '$1==p{print $2; exit}' "$hist")" - if [[ "$line" =~ ^[0-9]+$ ]]; then printf '%s' "$line"; return; fi - fi - printf '%s' "${PKGPOLICY_COMPILE_SECONDS[$pkg]:-300}" -} - -pkgpolicy_updates_per_year() { - local pkg="$1" hist line - hist="$(pkgpolicy_history_file)" - if [[ -r "$hist" ]]; then - line="$(awk -F'\t' -v p="$pkg" '$1==p{print $3; exit}' "$hist")" - if [[ "$line" =~ ^[0-9]+$ ]]; then printf '%s' "$line"; return; fi - fi - printf '6' -} - -# pkgpolicy_binary_available PKG - a binary can plausibly be fetched -pkgpolicy_binary_available() { - [[ -n "$(config_get BINHOST_URI)" ]] || return 1 - config_bool FEATURES_BINPKG -} - -# pkgpolicy_decide PKG - prints "source" or "binary" -pkgpolicy_decide() { - local pkg="$1" policy seconds mem cores - policy="$(config_get PACKAGE_POLICY)" - seconds="$(pkgpolicy_compile_seconds "$pkg")" - mem="$(hw_mem_total_mib)"; [[ -n "$mem" ]] || mem=4096 - cores="$(hw_cpu_cores)"; [[ -n "$cores" ]] || cores=2 - - case "$policy" in - source_first) - printf 'source'; return ;; - binary_first) - if pkgpolicy_binary_available; then printf 'binary'; else printf 'source'; fi - return ;; - esac - - # balanced: - # - explicit preferences win; - # - cheap builds are compiled locally; - # - everything else uses a signed Gentoo binary when one is available. - # This is deterministic and avoids guessing performance where no data - # exists. Portage still builds from source whenever USE does not match the - # binary (--binpkg-respect-use=y). - if [[ -n "${PKGPOLICY_BINARY_PREFERRED[$pkg]:-}" ]]; then - pkgpolicy_binary_available && { printf 'binary'; return; } - fi - if [[ -n "${PKGPOLICY_SOURCE_PREFERRED[$pkg]:-}" ]]; then - printf 'source'; return - fi - if ((seconds <= 120)); then printf 'source'; return; fi - if pkgpolicy_binary_available; then printf 'binary'; return; fi - printf 'source' -} - -# pkgpolicy_emerge_flags PKG - extra emerge flags for a package -pkgpolicy_emerge_flags() { - local pkg="$1" decision - decision="$(pkgpolicy_decide "$pkg")" - if [[ "$decision" == "binary" ]]; then - printf '%s\n' --getbinpkg --binpkg-respect-use=y - fi -} - -# pkgpolicy_report [PKGS...] - human readable policy decisions -pkgpolicy_report() { - local -a pkgs=("$@") pkg - ((${#pkgs[@]})) || pkgs=(sys-apps/systemd sys-devel/gcc www-client/firefox sys-kernel/gentoo-kernel app-editors/vim) - printf 'Policy: %s\n\n' "$(config_get PACKAGE_POLICY)" - printf '%-32s %8s %s\n' "package" "est(s)" "decision" - for pkg in "${pkgs[@]}"; do - printf '%-32s %8s %s\n' "$pkg" "$(pkgpolicy_compile_seconds "$pkg")" "$(pkgpolicy_decide "$pkg")" - done -} diff --git a/installer/lib/plan.sh b/installer/lib/plan.sh deleted file mode 100644 index a944399..0000000 --- a/installer/lib/plan.sh +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Installation plan generation. -# -# The plan is a deterministic, human-readable description of the operations the -# backend will perform. Nothing is executed until the plan has been displayed -# and explicitly approved (see install.sh). - -declare -ga PLAN_LINES=() -declare -ga PLAN_STEPS=() - -_plan_add() { PLAN_LINES+=("$@"); } -_step() { PLAN_STEPS+=("$*"); } - -# plan_swap_mib - swapfile size in MiB derived from installed RAM -plan_swap_mib() { - local mem - mem="$(hw_mem_total_mib)" - [[ -n "$mem" ]] || mem=4096 - local swap=$((mem / 2)) - ((swap < 1024)) && swap=1024 - ((swap > 8192)) && swap=8192 - printf '%s' "$swap" -} - -# plan_storage_sizes - sets PLAN_EFI_MIB and PLAN_LUKS_MIB -plan_storage_sizes() { - local disk="${1:-$(config_get TARGET_DISK)}" total efi - PLAN_EFI_MIB="$(config_get EFI_SIZE_MIB)" - [[ "$PLAN_EFI_MIB" =~ ^[0-9]+$ ]] || PLAN_EFI_MIB=1024 - total=0 - if [[ -b "$disk" ]]; then - total="$(disk_size_bytes "$disk")" - fi - PLAN_LUKS_MIB=$(( (total / 1048576) - PLAN_EFI_MIB - 2 )) - ((PLAN_LUKS_MIB < 0)) && PLAN_LUKS_MIB=0 -} - -# plan_generate - build PLAN_LINES and PLAN_STEPS from CFG -plan_generate() { - PLAN_LINES=() - PLAN_STEPS=() - - local disk hostname locale tz username fs enc kprofile desktop policy - disk="$(config_get TARGET_DISK)" - hostname="$(config_get HOSTNAME)" - locale="$(config_get LOCALE)" - tz="$(config_get TIMEZONE)" - username="$(config_get USERNAME)" - fs="$(config_get FILESYSTEM)" - enc="$(config_get ENCRYPTION)" - kprofile="$(config_get KERNEL_PROFILE)" - desktop="$(config_get DESKTOP_PROFILE)" - policy="$(config_get PACKAGE_POLICY)" - - _plan_add "Installation plan" - _plan_add "=================" - _plan_add "" - _plan_add "System:" - _plan_add " Distribution : $(config_get DISTRO_NAME)" - _plan_add " Architecture : $(config_get ARCH)" - _plan_add " Init system : $(config_get INIT_SYSTEM)" - _plan_add " Firmware : $(hw_firmware_mode)" - _plan_add "" - _plan_add "Identity:" - _plan_add " Hostname : $hostname" - _plan_add " Keymap : $(config_get KEYMAP)" - _plan_add " Locale : $locale" - _plan_add " Timezone : $tz" - _plan_add " User : ${username:-}" - _plan_add "" - _plan_add "Storage:" - _plan_add " Target disk : ${disk:-}" - if [[ -n "$disk" && -b "$disk" ]]; then - _plan_add " Disk model : $(disk_model "$disk")" - _plan_add " Disk size : $(disk_size_human "$(disk_size_bytes "$disk")")" - fi - _plan_add " Partitioning : GPT (${PARTITION_SCHEME:-whole_disk})" - _plan_add " Encryption : ${enc:-none}" - _plan_add " Filesystem : $fs" - _plan_add "" - _plan_add " Layout:" - _plan_add " EFI System Partition (FAT32) $(config_get EFI_SIZE_MIB) MiB -> $(config_get EFI_MOUNT)" - _plan_add " $(printf '%-36s' "${enc^^} container") remainder" - _plan_add " $(printf '%-34s' "$fs")" - local subvol - for subvol in $(config_get BTRFS_SUBVOLS); do - _plan_add " $subvol" - done - _plan_add "" - _plan_add "Boot and kernel:" - _plan_add " Bootloader : $(config_get BOOTLOADER) (BLS entries)" - _plan_add " Unified UKI : $(config_get KERNEL_UKI) (deferred; BLS used)" - _plan_add " Kernel : $(kernel_select_package 2>/dev/null || config_get KERNEL_PACKAGE) ($kprofile profile)" - _plan_add " Keep kernels : $(config_get KEEP_KERNELS)" - _plan_add "" - _plan_add "Software:" - _plan_add " Package policy : $policy" - _plan_add " Binary pkgs : $(config_get FEATURES_BINPKG)" - _plan_add " Accept license : $(config_get ACCEPT_LICENSE)" - _plan_add " Desktop : $desktop" - _plan_add " Flatpak : $(config_get FLATPAK)" - _plan_add " Audio : $(config_get AUDIO_STACK)" - _plan_add " AI assistant : $(config_get AI_ENABLED)" - - # Ordered execution steps (names map to backend functions in install.sh). - _step "storage_prepare" - _step "stage_install" - _step "fstab_generate" - _step "portage_configure" - _step "packages_base" - _step "kernel_install" - _step "boot_install" - _step "users_configure" - _step "services_configure" - _step "desktop_install" - _step "finalize" -} - -# plan_render - print the full plan -plan_render() { printf '%s\n' "${PLAN_LINES[@]}"; } - -# plan_destructive_preview - the scary, explicit summary shown before wiping -plan_destructive_preview() { - local disk enc fs - disk="$(config_get TARGET_DISK)" - enc="$(config_get ENCRYPTION)" - fs="$(config_get FILESYSTEM)" - printf 'TARGET: %s\n' "$disk" - printf '\n' - printf 'ALL DATA ON THIS DEVICE WILL BE DESTROYED.\n' - printf 'This cannot be undone.\n' - printf '\n' - printf ' EFI (FAT32): %s MiB\n' "$(config_get EFI_SIZE_MIB)" - if [[ "$enc" != "none" && -n "$enc" ]]; then - printf ' %s (passphrase): remainder\n' "${enc^^}" - fi - printf ' %s:\n' "$fs" - local subvol - for subvol in $(config_get BTRFS_SUBVOLS); do - printf ' %s\n' "$subvol" - done - printf '\n' - printf 'Existing partitions on the target:\n' - disk_layout_text "$disk" 2>/dev/null | sed 's/^/ /' -} diff --git a/installer/lib/portage.sh b/installer/lib/portage.sh deleted file mode 100644 index 54c3cd3..0000000 --- a/installer/lib/portage.sh +++ /dev/null @@ -1,363 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Portage configuration and base-system installation. -# -# Portage stays the authoritative package manager. This module writes a -# sensible initial configuration, resolves the stable systemd stage3 and runs -# emerge inside the target chroot. - -# portage_detect_cpu_flags - CPU_FLAGS_X86 from /proc/cpuinfo (deterministic) -portage_detect_cpu_flags() { - local -a wanted=(aes avx avx2 avx512f avx512bw avx512cd avx512dq avx512vl - bmi1 bmi2 f16c fma mmx mmxext pclmul popcnt rdrand sha sse sse2 sse3 - sse4_1 sse4_2 ssse3 xop) - local -A flags=() - local f w - for f in $(awk -F': ' '/^flags/{print $2; exit}' /proc/cpuinfo 2>/dev/null); do - flags[$f]=1 - done - local out=() - for w in "${wanted[@]}"; do - [[ -n "${flags[$w]:-}" ]] && out+=("$w") - done - printf '%s' "${out[*]}" -} - -portage_detect_video_cards() { - local vendors cards=() - vendors="$(hw_gpu_vendors)" - [[ "$vendors" == *intel* ]] && cards+=(intel) - [[ "$vendors" == *amd* ]] && cards+=(amdgpu radeonsi) - [[ "$vendors" == *nvidia* ]] && cards+=(nvidia) - ((${#cards[@]})) || cards+=(dummy) - printf '%s' "${cards[*]}" -} - -# portage_makeopts - parallel build width bounded by RAM -portage_makeopts() { - local cores mem jobs load - cores="$(hw_cpu_cores)"; [[ "$cores" =~ ^[0-9]+$ ]] || cores=4 - mem="$(hw_mem_total_mib)"; [[ "$mem" =~ ^[0-9]+$ ]] || mem=4096 - jobs=$((cores + 1)) - local mem_jobs=$((mem / 2048)) - ((mem_jobs < 1)) && mem_jobs=1 - ((jobs > mem_jobs)) && jobs=$mem_jobs - ((jobs < 1)) && jobs=1 - load="$cores" - printf -- '-j%s -l%s' "$jobs" "$load" -} - -portage_write_make_conf() { - local root="$1" - local mac="$root/etc/portage/make.conf" - mkdir -p "$(dirname "$mac")" - { - printf '# %s Portage configuration\n' "$(config_get DISTRO_NAME)" - printf '# Generated by the installer. Safe to edit.\n\n' - printf 'COMMON_FLAGS="-O2 -pipe -march=native"\n' - printf 'CFLAGS="${COMMON_FLAGS}"\n' - printf 'CXXFLAGS="${COMMON_FLAGS}"\n' - printf 'FCFLAGS="${COMMON_FLAGS}"\n' - printf 'FFLAGS="${COMMON_FLAGS}"\n\n' - printf 'MAKEOPTS="%s"\n' "$(portage_makeopts)" - printf 'EMERGE_DEFAULT_OPTS="--binpkg-respect-use=y --with-bdeps=y"\n\n' - printf 'ACCEPT_KEYWORDS="amd64"\n' - printf 'ACCEPT_LICENSE="%s"\n\n' "$(config_get ACCEPT_LICENSE)" - printf '# Keep the global USE set close to the profile/binhost baseline so that\n' - printf '# signed binaries can be reused; per-package USE lives in package.use.\n' - printf '# dbus/policykit are part of the standard systemd desktop baseline and\n' - printf '# are required by NetworkManager/wpa_supplicant and polkit respectively.\n' - printf 'USE="systemd dbus policykit"\n' - printf 'VIDEO_CARDS="%s"\n' "$(portage_detect_video_cards)" - printf 'INPUT_DEVICES="libinput"\n' - printf 'LINGUAS="en"\n' - } >"$mac" - log_info "wrote $mac" -} - -portage_write_repos_conf() { - local root="$1" - local dir="$root/etc/portage/repos.conf" - mkdir -p "$dir" - { - printf '[gentoo]\n' - printf 'location = /var/db/repos/gentoo\n' - printf 'sync-type = rsync\n' - printf 'sync-uri = rsync://rsync.gentoo.org/gentoo-portage\n' - printf 'auto-sync = yes\n' - } >"$dir/gentoo.conf" - log_info "wrote $dir/gentoo.conf" -} - -portage_write_binrepos() { - local root="$1" - local dir="$root/etc/portage/binrepos.conf" - mkdir -p "$dir" - { - printf '[gentoo]\n' - printf 'priority = 1\n' - printf 'sync-uri = %s\n' "$(config_get BINHOST_URI)" - printf 'location = /var/cache/binhost/gentoo\n' - printf 'verify-signature = true\n' - } >"$dir/gentoo.conf" - log_info "wrote $dir/gentoo.conf" -} - -portage_write_package_files() { - local root="$1" - local dir="$root/etc/portage/package.use" - mkdir -p "$dir" - { - printf '# %s installer policy\n' "$(config_get DISTRO_NAME)" - printf '# Core system: systemd is the init system.\n' - printf '# policykit is required by sys-auth/polkit[systemd];\n' - printf '# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n' - printf 'sys-apps/systemd boot policykit cryptsetup\n' - printf '# Distribution kernel + systemd-boot UKI generation.\n' - printf '# installkernel REQUIRED_USE: systemd-boot? ( systemd ), ukify? ( uki )\n' - printf 'sys-kernel/installkernel dracut systemd systemd-boot uki\n' - printf 'sys-apps/dbus systemd\n' - printf 'sys-auth/polkit systemd\n' - printf 'sys-apps/util-linux systemd\n' - printf '# Networking\n' - printf 'net-misc/networkmanager systemd\n' - printf '# Audio (PipeWire + WirePlumber are the standard stack)\n' - printf 'media-video/pipewire sound-server\n' - printf 'media-video/wireplumber\n' - if [[ "$(config_get DESKTOP_PROFILE)" != "none" ]]; then - # Wayland-first, but GTK3/polkit-gnome still need cairo/gtk built with - # X support (XWayland and the GTK X11 backend). Keep Wayland enabled too. - printf '# Desktop (Wayland-first, XWayland compatibility)\n' - printf 'x11-libs/cairo X\n' - printf 'x11-libs/gtk+ X wayland\n' - printf 'gui-libs/gtk wayland\n' - printf 'media-libs/libglvnd X\n' - printf 'x11-terms/kitty wayland\n' - printf 'media-video/pipewire systemd\n' - fi - } >"$dir/phoebus" - log_info "wrote $dir/phoebus" - - # Narrowly scoped testing keywords. Gentoo currently keywords linux-firmware - # and some Wayland components as testing-only; these are hardware/desktop - # enablement and are justified explicitly rather than globally enabling - # ~amd64. - local ak="$root/etc/portage/package.accept_keywords" - mkdir -p "$ak" - { - printf '# Phoebus: scoped testing keywords for hardware/desktop enablement.\n' - printf '# This is NOT a global ~amd64 switch.\n' - printf 'sys-kernel/linux-firmware\n' - printf 'gui-wm/dwl\n' - } >"$ak/phoebus" - log_info "wrote $ak/phoebus" -} - -# portage_select_profile ROOT -portage_select_profile() { - local root="$1" profile - profile="$(config_get GENTOO_PROFILE)" - local link="$root/etc/portage/make.profile" - mkdir -p "$(dirname "$link")" - rm -f "$link" - ln -s "/var/db/repos/gentoo/profiles/$profile" "$link" - log_info "profile -> $profile" -} - -# portage_stage3_url - resolve the stable systemd stage3 URL -portage_stage3_url() { - local pinned - pinned="$(config_get STAGE3_URL)" - if [[ -n "$pinned" ]]; then printf '%s' "$pinned"; return 0; fi - local base latest rel - base="$(config_get STAGE3_MIRROR)" - latest="$base/current-stage3-amd64-systemd/latest-stage3-amd64-systemd.txt" - if command -v curl >/dev/null 2>&1; then - # The latest-*.txt file is PGP-clearsigned and contains a line such as: - # stage3-amd64-systemd-20260913T163055Z.tar.xz 290634984 - rel="$(curl -fsSL "$latest" 2>/dev/null | \ - awk '$1 ~ /^stage3-amd64-systemd-.*\.tar\.xz$/{print $1; exit}')" - fi - if [[ -z "$rel" ]]; then - log_warn "could not resolve latest stage3 (offline?); set STAGE3_URL explicitly" - return 1 - fi - printf '%s/current-stage3-amd64-systemd/%s' "$base" "$rel" -} - -# portage_verify_stage3_signature FILE -# Verifies the clearsigned DIGESTS file with the Gentoo release key that the -# stage3 ships. Fails closed when gpg and the key are available. -portage_verify_stage3_signature() { - local digests="$1" key="/usr/share/openpgp-keys/gentoo-release.asc" home rc=0 - command -v gpg >/dev/null 2>&1 || { log_warn "gpg unavailable; skipping signature check"; return 0; } - [[ -r "$key" ]] || { log_warn "Gentoo release key not found; skipping signature check"; return 0; } - home="$(mktemp -d)" - if ! GNUPGHOME="$home" gpg --batch --quiet --import "$key" >/dev/null 2>>"$PHOEBUS_LOG_FILE" 2>&1; then - log_warn "could not import Gentoo release key; skipping signature check" - rm -rf "$home" - return 0 - fi - if GNUPGHOME="$home" gpg --batch --verify "$digests" >>"$PHOEBUS_LOG_FILE" 2>&1; then - log_info "stage3 DIGESTS signature verified" - else - log_error "stage3 DIGESTS signature verification FAILED" - rc=1 - fi - rm -rf "$home" - return $rc -} - -# portage_fetch_stage3 DESTDIR - download and verify the stage3 tarball -portage_fetch_stage3() { - local dest="$1" url base expected got want digests - url="$(portage_stage3_url)" || return 1 - base="${url##*/}" - expected="$(config_get STAGE3_SHA256)" - log_info "stage3 URL: $url" - run_cmd "download stage3" curl -fL --retry 3 -o "$dest" "$url" || return 1 - - if [[ -n "$expected" ]]; then - got="$(sha256sum "$dest" | awk '{print $1}')" - if [[ "$got" != "$expected" ]]; then - log_error "stage3 checksum mismatch (expected $expected, got $got)" - return 1 - fi - log_info "stage3 checksum verified (pinned SHA-256)" - return 0 - fi - - digests="${dest}.DIGESTS" - if ! run_cmd "download stage3 DIGESTS" curl -fsSL -o "$digests" "$url.DIGESTS"; then - log_warn "could not fetch stage3 DIGESTS; checksum not verified" - return 0 - fi - portage_verify_stage3_signature "$digests" || return 1 - want="$(awk -v f="$base" 'length($1)==128 && $2==f{print $1; exit}' "$digests")" - if [[ -z "$want" ]]; then - log_warn "no SHA-512 entry for $base in DIGESTS" - rm -f "$digests" - return 0 - fi - got="$(sha512sum "$dest" | awk '{print $1}')" - rm -f "$digests" - if [[ "$got" != "$want" ]]; then - log_error "stage3 SHA-512 mismatch (expected $want, got $got)" - return 1 - fi - log_info "stage3 SHA-512 verified against signed DIGESTS" - return 0 -} - -# portage_extract_stage3 ROOT TARBALL -portage_extract_stage3() { - local root="$1" tarball="$2" - run_destructive "extract stage3 into $root" \ - tar --xattrs --xattrs-include='*.*' --numeric-owner -xpf "$tarball" -C "$root" -} - -# portage_chroot ROOT CMD... - run a command inside the target -portage_chroot() { - local root="$1"; shift - run_cmd "chroot: $*" chroot "$root" \ - /usr/bin/env -i \ - PATH=/usr/sbin:/usr/bin:/sbin:/bin \ - HOME=/root TERM="${TERM:-xterm}" LANG=C TMPDIR=/tmp \ - "$@" -} - -# portage_chroot_stdin ROOT INPUT CMD... - chroot with INPUT on stdin. -# Used for secrets such as password hashes; INPUT is never logged. -portage_chroot_stdin() { - local root="$1" input="$2"; shift 2 - if config_bool DRY_RUN; then - log_line INFO "[dry-run] chroot: $* (stdin hidden)" - return 0 - fi - log_line INFO "chroot: $* (stdin hidden)" - printf '%s\n' "$input" | chroot "$root" \ - /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root LANG=C TMPDIR=/tmp \ - "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 - local status=$? - log_line INFO "chroot: $* :: exit status $status" - return $status -} - -# portage_base_packages - packages every Phoebus system needs beyond stage3. -# cryptsetup and btrfs-progs are required by dracut to build an initramfs that -# can unlock and mount the encrypted Btrfs root. -portage_base_packages() { - printf '%s\n' \ - app-admin/sudo \ - net-misc/networkmanager \ - sys-auth/polkit \ - sys-fs/cryptsetup \ - sys-fs/btrfs-progs -} - -# portage_sync ROOT - initialise the repository over rsync (rsync ships in the -# stage3; curl/wget do not). -portage_sync() { - local root="$1" - portage_chroot "$root" emerge --sync -} - -# portage_verification_setup ROOT -# Populate /etc/portage/gnupg with the Gentoo release key so that signed -# binary packages can be verified. getuto ships in the stage3. -portage_verification_setup() { - local root="$1" - portage_chroot "$root" getuto -} - -# portage_init_machine_id ROOT -# The systemd stage3 ships no /etc/machine-id. Generate one before the kernel -# is installed so kernel-install has stable machine identification. -portage_init_machine_id() { - local root="$1" - portage_chroot "$root" systemd-machine-id-setup -} - -# portage_write_locale_gen ROOT LOCALE - ensure the chosen locale is generated -portage_write_locale_gen() { - local root="$1" locale="$2" file="$1/etc/locale.gen" - [[ -n "$locale" ]] || return 0 - [[ -f "$file" ]] || { mkdir -p "$root/etc"; : >"$file"; } - if ! grep -qE "^[[:space:]]*${locale//./\\.}[[:space:]]" "$file"; then - printf '%s UTF-8\n' "$locale" >>"$file" - log_info "locale.gen: enabled $locale" - fi -} - -# portage_emerge ROOT PACKAGES... -# Group packages by policy decision and run one emerge per group. This keeps -# the dependency graph solve to a minimum and passes --getbinpkg only to the -# group that should prefer binaries. -portage_emerge() { - local root="$1"; shift - local pkg decision - local -a bin_pkgs=() src_pkgs=() - for pkg in "$@"; do - [[ -n "$pkg" ]] || continue - decision="$(pkgpolicy_decide "$pkg")" - log_info "policy: $pkg -> $decision" - if [[ "$decision" == "binary" ]]; then - bin_pkgs+=("$pkg") - else - src_pkgs+=("$pkg") - fi - done - local status=0 - if ((${#src_pkgs[@]})); then - log_info "emerge (source): ${src_pkgs[*]}" - portage_chroot "$root" emerge --ask=n --quiet-build=y \ - --binpkg-respect-use=y "${src_pkgs[@]}" || { log_error "source emerge failed"; status=1; } - fi - if ((status == 0 && ${#bin_pkgs[@]})); then - log_info "emerge (binary): ${bin_pkgs[*]}" - portage_chroot "$root" emerge --ask=n --quiet-build=y \ - --getbinpkg --binpkg-respect-use=y "${bin_pkgs[@]}" || { log_error "binary emerge failed"; status=1; } - fi - return $status -} diff --git a/installer/lib/state.sh b/installer/lib/state.sh deleted file mode 100644 index cd4c680..0000000 --- a/installer/lib/state.sh +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Installer configuration state. -# -# All user choices live in the associative array CFG. The state is deliberately -# kept separate from the UI so that an unattended installation can be driven -# from a plain configuration file. - -declare -gA CFG=() -declare -g CONFIG_FILE="${CONFIG_FILE:-}" - -# config_default KEY VALUE -# Set KEY to VALUE only when it has not been set yet. This lets a user -# config file loaded later override the shipped defaults. -config_default() { - local key="$1" value="${2-}" - if [[ -z "${CFG[$key]+set}" ]]; then - CFG[$key]="$value" - fi -} - -# config_set KEY VALUE -config_set() { - local key="$1" value="${2-}" - CFG[$key]="$value" -} - -# config_get KEY [DEFAULT] -config_get() { - local key="$1" default="${2-}" - if [[ -n "${CFG[$key]+set}" ]]; then - printf '%s' "${CFG[$key]}" - else - printf '%s' "$default" - fi -} - -# config_is KEY VALUE - boolean helper -config_is() { - [[ "$(config_get "$1")" == "$2" ]] -} - -config_bool() { - case "$(config_get "$1")" in - yes|true|1|on) return 0 ;; - *) return 1 ;; - esac -} - -# config_load_defaults [FILE] -config_load_defaults() { - local file="${1:-$PHOEBUS_ROOT/config/defaults.conf}" - [[ -r "$file" ]] || return 1 - # shellcheck source=/dev/null - source "$file" -} - -# Decode a value from a config file. Supports plain, single- and double-quoted -# values. This is not a general shell evaluator on purpose: configuration files -# are data, and must never execute code. -config_decode_value() { - local raw="$1" - case "$raw" in - \'*\') - raw="${raw#\'}" - raw="${raw%\'}" - raw="${raw//\'\\\'\'/\'}" - ;; - \"*\") - raw="${raw#\"}" - raw="${raw%\"}" - ;; - esac - printf '%s' "$raw" -} - -# config_load_file FILE -config_load_file() { - local file="$1" line key value - [[ -r "$file" ]] || return 1 - while IFS= read -r line || [[ -n "$line" ]]; do - [[ "$line" =~ ^[[:space:]]*# ]] && continue - [[ "$line" =~ ^[[:space:]]*$ ]] && continue - if [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then - key="${BASH_REMATCH[1]}" - value="$(config_decode_value "${BASH_REMATCH[2]}")" - CFG[$key]="$value" - fi - done <"$file" - CONFIG_FILE="$file" -} - -# config_save_file FILE -config_save_file() { - local file="$1" key - local dir - dir="$(dirname -- "$file")" - mkdir -p "$dir" - { - printf '# Phoebus OS installer configuration\n' - printf '# Generated: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)" - printf '# NOTE: never place passwords, passphrases or API keys in this file.\n\n' - local -a keys - mapfile -t keys < <(printf '%s\n' "${!CFG[@]}" | sort) - for key in "${keys[@]}"; do - case "$key" in - LUKS_PASSPHRASE|ROOT_PASSWORD|USER_PASSWORD|AI_API_KEY) - continue ;; - esac - printf "%s='%s'\n" "$key" "${CFG[$key]//\'/\'\\\'\'}" - done - } >"$file" -} - -# config_summary - stable, sorted KEY=value dump (for logs, values redacted) -config_dump() { - local key - local -a keys - mapfile -t keys < <(printf '%s\n' "${!CFG[@]}" | sort) - for key in "${keys[@]}"; do - printf '%s=%s\n' "$key" "$(redact_value "$key" "${CFG[$key]}")" - done -} - -# redact_value KEY VALUE - never emit secret material -redact_value() { - local key="$1" value="$2" - case "$key" in - *PASSWORD*|*PASSPHRASE*|*API_KEY*|*TOKEN*|*SECRET*) - if [[ -n "$value" ]]; then printf ''; else printf ''; fi - ;; - *) printf '%s' "$value" ;; - esac -} diff --git a/installer/lib/users.sh b/installer/lib/users.sh deleted file mode 100644 index 63c1443..0000000 --- a/installer/lib/users.sh +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# User account configuration. -# -# Passwords are hashed immediately and held only as hashes. Plaintext is never -# written to disk, the config file or the log. - -declare -g USER_PASSWORD="${USER_PASSWORD:-}" -declare -g ROOT_PASSWORD="${ROOT_PASSWORD:-}" - -# users_hash PASSWORD - SHA-512 crypt hash (openssl present in the live image) -users_hash() { - local pw="$1" hash - if command -v openssl >/dev/null 2>&1; then - hash="$(printf '%s' "$pw" | openssl passwd -6 -stdin 2>/dev/null)" - fi - [[ -n "$hash" ]] || return 1 - printf '%s' "$hash" -} - -# users_prompt_passwords - collect and hash passwords (TUI or tty) -users_prompt_passwords() { - local user rootpw - if declare -F ui_passwordbox >/dev/null 2>&1; then - ui_passwordbox "User password" "Password for $(config_get USERNAME):" || return 1 - user="$UI_RESULT" - ui_passwordbox "User password" "Repeat password:" || return 1 - [[ "$user" == "$UI_RESULT" ]] || { log_error "user passwords did not match"; return 1; } - ui_passwordbox "Root password" "Password for root (leave blank to lock root):" || return 1 - rootpw="$UI_RESULT" - else - read -r -s -p "User password: " user; printf '\n' >&2 - read -r -s -p "Root password (blank to lock): " rootpw; printf '\n' >&2 - fi - secret_register "$user" - secret_register "$rootpw" - USER_PASSWORD="$user" - ROOT_PASSWORD="$rootpw" - return 0 -} - -# users_create ROOT - create the primary account and lock root by default -# users_ensure_groups ROOT GROUPS -# Create missing supplementary groups and return the subset that now exists. -# A minimal stage3 does not define render/libinput/plugdev/power, and -# useradd -G fails outright if any listed group is absent. -users_ensure_groups() { - local root="$1" groups="$2" g out="" - local saved_ifs="$IFS" - IFS=, - for g in $groups; do - [[ -z "$g" ]] && continue - if ! grep -q "^$g:" "$root/etc/group" 2>/dev/null; then - portage_chroot "$root" groupadd -r "$g" || log_warn "could not create group $g" - fi - if grep -q "^$g:" "$root/etc/group" 2>/dev/null; then - out="${out:+$out,}$g" - else - log_warn "group $g not available; skipping" - fi - done - IFS="$saved_ifs" - printf '%s' "$out" -} - -users_create() { - local root="$1" username fullname groups shell userhash roothash - username="$(config_get USERNAME)" - fullname="$(config_get USER_FULLNAME)" - shell="$(config_get ROOT_SHELL)" - [[ -n "$username" ]] || { log_error "no username configured"; return 1; } - - groups="$(users_ensure_groups "$root" "$(config_get USER_GROUPS)")" - local -a uargs=(-m -U -s "$shell" -c "$fullname") - [[ -n "$groups" ]] && uargs+=(-G "$groups") - uargs+=("$username") - portage_chroot "$root" useradd "${uargs[@]}" || { - log_error "useradd failed"; return 1; } - - userhash="$(users_hash "$USER_PASSWORD")" - if [[ -n "$userhash" ]]; then - portage_chroot_stdin "$root" "$username:$userhash" chpasswd -e || { - log_error "could not set password for $username"; return 1; } - log_info "password set for $username" - else - log_warn "no password set for $username (account locked)" - fi - - if [[ -n "$ROOT_PASSWORD" ]]; then - roothash="$(users_hash "$ROOT_PASSWORD")" - portage_chroot_stdin "$root" "root:$roothash" chpasswd -e || { - log_warn "could not set root password"; } - log_info "root password set" - else - portage_chroot "$root" passwd -l root || true - log_info "root account locked (no root password supplied)" - fi - USER_PASSWORD="" ROOT_PASSWORD="" -} - -# users_configure_sudo ROOT - wheel group may sudo, with a password -users_configure_sudo() { - local root="$1" - local dir="$root/etc/sudoers.d" - mkdir -p "$dir" - { - printf '# Members of the wheel group may run commands as root.\n' - printf '%%wheel ALL=(ALL:ALL) ALL\n' - } >"$dir/10-wheel" - chmod 0440 "$dir/10-wheel" - if [[ -x "$root/usr/sbin/visudo" || -x "$root/sbin/visudo" ]]; then - portage_chroot "$root" visudo -cf /etc/sudoers.d/10-wheel || { - log_error "invalid sudoers file"; return 1; } - fi - log_info "sudo configured for wheel" -} - -# users_verify ROOT -users_verify() { - local root="$1" username - username="$(config_get USERNAME)" - grep -q "^$username:" "$root/etc/passwd" || { - log_error "user $username missing from target"; return 1; } - [[ -d "$root/home/$username" ]] || log_warn "home directory for $username not found" - return 0 -} diff --git a/installer/lib/validation.sh b/installer/lib/validation.sh deleted file mode 100644 index 039176b..0000000 --- a/installer/lib/validation.sh +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Configuration validation. -# -# Pure(ish) decision logic, separated from the TUI so it can be unit tested and -# reused for unattended installs. validate_config prints one problem per line -# and returns the number of problems found. - -validate_hostname() { - local h="$1" - [[ ${#h} -ge 1 && ${#h} -le 63 ]] || { printf 'hostname must be 1-63 characters\n'; return 1; } - [[ "$h" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$ ]] || { - printf 'hostname may only contain letters, digits and internal hyphens\n'; return 1; } - return 0 -} - -validate_username() { - local u="$1" - [[ -n "$u" ]] || { printf 'username is required\n'; return 1; } - [[ "$u" != "root" ]] || { printf 'refusing to create an account named root\n'; return 1; } - [[ ${#u} -le 32 ]] || { printf 'username must be at most 32 characters\n'; return 1; } - [[ "$u" =~ ^[a-z_][a-z0-9_-]*$ ]] || { - printf 'username must start with a lowercase letter and contain only [a-z0-9_-]\n'; return 1; } - return 0 -} - -validate_locale() { - local l="$1" - [[ -n "$l" ]] || { printf 'locale is required\n'; return 1; } - local base="${l%%.*}" - if [[ -r /usr/share/i18n/locales/$base ]] || \ - [[ -d /usr/lib/locale && -e /usr/lib/locale/locale-archive ]]; then - return 0 - fi - [[ "$l" =~ ^[A-Za-z_]+\.?[A-Za-z0-9-]*$ ]] && return 0 - printf 'locale looks malformed: %s\n' "$l" - return 1 -} - -validate_timezone() { - local tz="$1" - [[ -n "$tz" ]] || { printf 'timezone is required\n'; return 1; } - if [[ -d /usr/share/zoneinfo ]]; then - [[ -e "/usr/share/zoneinfo/$tz" && ! -d "/usr/share/zoneinfo/$tz" ]] && return 0 - printf 'unknown timezone: %s\n' "$tz" - return 1 - fi - return 0 -} - -validate_keymap() { - local km="$1" - [[ -n "$km" ]] || { printf 'keymap is required\n'; return 1; } - return 0 -} - -validate_target_disk() { - local disk="$1" - [[ -n "$disk" ]] || { printf 'no target disk selected\n'; return 1; } - [[ -b "$disk" ]] || { printf 'target is not a block device: %s\n' "$disk"; return 1; } - local reason - reason="$(disk_protected_reason "$disk")" - if [[ -n "$reason" ]]; then - printf 'refusing target %s: %s\n' "$disk" "$reason" - return 1 - fi - return 0 -} - -# validate_config [KEYS...] - print problems; return problem count -validate_config() { - local -a keys=("$@") - local problems=0 msg - ((${#keys[@]})) || keys=(HOSTNAME USERNAME LOCALE TIMEZONE KEYMAP TARGET_DISK) - - local key - for key in "${keys[@]}"; do - case "$key" in - HOSTNAME) validate_hostname "$(config_get HOSTNAME)" && true || { problems=$((problems+1)); } ;; - USERNAME) validate_username "$(config_get USERNAME)" && true || { problems=$((problems+1)); } ;; - LOCALE) validate_locale "$(config_get LOCALE)" && true || { problems=$((problems+1)); } ;; - TIMEZONE) validate_timezone "$(config_get TIMEZONE)" && true || { problems=$((problems+1)); } ;; - KEYMAP) validate_keymap "$(config_get KEYMAP)" && true || { problems=$((problems+1)); } ;; - TARGET_DISK) validate_target_disk "$(config_get TARGET_DISK)" && true || { problems=$((problems+1)); } ;; - esac - done - return "$problems" -} - -# validate_password_strength PASSWORD - print a short assessment -validate_password_strength() { - local pw="$1" score=0 - ((${#pw} >= 8)) && score=$((score+1)) - ((${#pw} >= 12)) && score=$((score+1)) - [[ "$pw" =~ [A-Z] ]] && score=$((score+1)) - [[ "$pw" =~ [a-z] ]] && score=$((score+1)) - [[ "$pw" =~ [0-9] ]] && score=$((score+1)) - [[ "$pw" =~ [^A-Za-z0-9] ]] && score=$((score+1)) - if ((score <= 2)); then printf 'weak' - elif ((score <= 4)); then printf 'fair' - else printf 'strong'; fi -} diff --git a/installer/tests/lib.sh b/installer/tests/lib.sh deleted file mode 100644 index 0f6f41b..0000000 --- a/installer/tests/lib.sh +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Minimal test harness. No external test framework is required (the live image -# has none, and the backend must be testable on any machine). - -TESTS_RUN=0 -TESTS_FAILED=0 -TEST_NAME="unknown" - -phoebus_test_setup() { - # shellcheck source=/dev/null - PHOEBUS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" - export PHOEBUS_ROOT - STATE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/phoebus-test.XXXXXX")" - export STATE_DIR - PHOEBUS_LOG_FILE="$STATE_DIR/test.log" - export PHOEBUS_LOG_FILE - : >"$PHOEBUS_LOG_FILE" - PHOEBUS_LOG_ECHO=no - export PHOEBUS_LOG_ECHO - - local lib - for lib in state logging confirm hardware disks validation plan pkgpolicy \ - portage partitions filesystem encryption btrfs network kernel \ - boot users desktop opencode ai install; do - # shellcheck source=/dev/null - source "$PHOEBUS_ROOT/lib/$lib.sh" - done - config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf" -} - -_assert() { - local ok="$1" message="$2" - TESTS_RUN=$((TESTS_RUN + 1)) - if [[ "$ok" == "1" ]]; then - printf ' ok %s\n' "$message" - else - TESTS_FAILED=$((TESTS_FAILED + 1)) - printf ' FAIL %s\n' "$message" - fi -} - -assert_eq() { - local expected="$1" actual="$2" message="${3:-equal}" - if [[ "$expected" == "$actual" ]]; then _assert 1 "$message"; else - _assert 0 "$message (expected '$expected', got '$actual')"; fi -} - -assert_neq() { - local a="$1" b="$2" message="${3:-not equal}" - if [[ "$a" != "$b" ]]; then _assert 1 "$message"; else - _assert 0 "$message (both '$a')"; fi -} - -assert_contains() { - local haystack="$1" needle="$2" message="${3:-contains}" - if [[ "$haystack" == *"$needle"* ]]; then _assert 1 "$message"; else - _assert 0 "$message (missing '$needle')"; fi -} - -assert_not_contains() { - local haystack="$1" needle="$2" message="${3:-not contains}" - if [[ "$haystack" != *"$needle"* ]]; then _assert 1 "$message"; else - _assert 0 "$message (unexpectedly found '$needle')"; fi -} - -assert_success() { - local message="$1"; shift - if "$@" >/dev/null 2>&1; then _assert 1 "$message"; else _assert 0 "$message"; fi -} - -assert_failure() { - local message="$1"; shift - if "$@" >/dev/null 2>&1; then _assert 0 "$message"; else _assert 1 "$message"; fi -} - -phoebus_test_report() { - printf '\n%s: %d run, %d failed\n' "$TEST_NAME" "$TESTS_RUN" "$TESTS_FAILED" - [[ "$TESTS_FAILED" -eq 0 ]] -} diff --git a/installer/tests/run_tests.sh b/installer/tests/run_tests.sh deleted file mode 100755 index 186a7aa..0000000 --- a/installer/tests/run_tests.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Run all installer tests. No root privileges and no block devices required. - -set -uo pipefail -TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PHOEBUS_ROOT="$(cd "$TEST_DIR/.." && pwd)" -export PHOEBUS_ROOT - -total_failed=0 -total_run=0 -failed_tests=() - -for test in "$TEST_DIR"/test_*.sh; do - [[ -f "$test" ]] || continue - printf '\n== %s ==\n' "$(basename "$test")" - if bash "$test"; then - : - else - failed_tests+=("$(basename "$test")") - total_failed=$((total_failed + 1)) - fi -done - -printf '\n========================================\n' -if ((${#failed_tests[@]})); then - printf 'FAILED test files (%d):\n' "${#failed_tests[@]}" - printf ' %s\n' "${failed_tests[@]}" - exit 1 -fi -printf 'All tests passed.\n' -exit 0 diff --git a/installer/tests/test_ai.sh b/installer/tests/test_ai.sh deleted file mode 100644 index 12c6be6..0000000 --- a/installer/tests/test_ai.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_ai" -phoebus_test_setup - -parsed="$(ai_parse_json_kv '{"hostname":"foo","encryption":"luks2","count":3}')" -assert_contains "$parsed" "hostname=foo" "flat JSON parser: string" -assert_contains "$parsed" "encryption=luks2" "flat JSON parser: string 2" -assert_contains "$parsed" "count=3" "flat JSON parser: number" - -assert_success "HOSTNAME permitted" ai_key_allowed HOSTNAME -assert_failure "EVIL key refused" ai_key_allowed EVIL -assert_failure "LUKS_PASSPHRASE refused" ai_key_allowed LUKS_PASSPHRASE - -assert_eq "" "$(ai_validate_field ENCRYPTION luks2)" "valid encryption accepted" -assert_neq "" "$(ai_validate_field ENCRYPTION bogus)" "invalid encryption rejected" -assert_neq "" "$(ai_validate_field HOSTNAME 'bad host')" "invalid hostname rejected" -assert_neq "" "$(ai_validate_field TARGET_DISK /dev/nonexistent)" "invalid disk rejected" - -# applying a proposal with an out-of-whitelist key still validates known keys -before="$(config_get HOSTNAME)" -ai_apply_proposal '{"hostname":"good-host","evil":"rm -rf /"}' >/dev/null 2>&1 || true -assert_eq "good-host" "$(config_get HOSTNAME)" "valid proposal field applied" -assert_eq "" "$(config_get EVIL)" "unknown proposal field ignored" - -# offline translator -offline="$(ai_propose_offline "encrypt everything with btrfs and a desktop")" -assert_contains "$offline" '"encryption":"luks2"' "offline proposal sets luks2" -assert_contains "$offline" '"filesystem":"btrfs"' "offline proposal sets btrfs" -assert_contains "$offline" '"desktop_profile":"dwl"' "offline proposal sets desktop" - -# offline assistance never needs a model -assert_contains "$(ai_offline_response "encryption")" "LUKS2" "offline encryption help" - -phoebus_test_report diff --git a/installer/tests/test_btrfs_order.sh b/installer/tests/test_btrfs_order.sh deleted file mode 100644 index 41930b1..0000000 --- a/installer/tests/test_btrfs_order.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Regression test: subvolumes must be created before any subvol=@ mount is -# attempted. The first VM install failed because the layout was mounted before -# the subvolumes existed (mount exit 32). -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_btrfs_order" -phoebus_test_setup -source "$PHOEBUS_ROOT/lib/confirm.sh" - -# Authorize destructive pseudo-commands for the fake environment. -PHOEBUS_DESTRUCTIVE_AUTHORIZED="yes" -config_set DRY_RUN "no" - -fakebin="$STATE_DIR/bin" -mkdir -p "$fakebin" -export FAKE_LOG="$STATE_DIR/calls.log" -: >"$FAKE_LOG" - -cat >"$fakebin/mount" <<'EOF' -#!/usr/bin/env bash -printf 'mount %s\n' "$*" >>"$FAKE_LOG" -exit 0 -EOF -cat >"$fakebin/umount" <<'EOF' -#!/usr/bin/env bash -printf 'umount %s\n' "$*" >>"$FAKE_LOG" -exit 0 -EOF -cat >"$fakebin/btrfs" <<'EOF' -#!/usr/bin/env bash -printf 'btrfs %s\n' "$*" >>"$FAKE_LOG" -exit 0 -EOF -chmod +x "$fakebin/mount" "$fakebin/umount" "$fakebin/btrfs" -PATH="$fakebin:$PATH" - -config_set BTRFS_SUBVOLS "@ @home @var @snapshots @swap" -btrfs_create_layout /dev/fake "$STATE_DIR/root" >/dev/null 2>&1 -rc=$? - -assert_eq "0" "$rc" "btrfs_create_layout succeeds with fake tools" - -# The first subvolume creation must precede the first subvol=@ mount. -create_line="$(grep -n 'btrfs subvolume create' "$FAKE_LOG" | head -n1 | cut -d: -f1)" -mount_line="$(grep -n 'subvol=@ ' "$FAKE_LOG" | head -n1 | cut -d: -f1)" -assert_success "subvolume create recorded" test -n "$create_line" -assert_success "subvol=@ mount recorded" test -n "$mount_line" -if [[ -n "$create_line" && -n "$mount_line" ]]; then - assert_success "subvolumes created before mounting @" test "$create_line" -lt "$mount_line" -fi - -# All five subvolumes are created. -assert_eq "5" "$(grep -c 'btrfs subvolume create' "$FAKE_LOG")" "all subvolumes created" - -phoebus_test_report diff --git a/installer/tests/test_install_dryrun.sh b/installer/tests/test_install_dryrun.sh deleted file mode 100644 index 1c8ba08..0000000 --- a/installer/tests/test_install_dryrun.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_install_dryrun" -phoebus_test_setup -source "$PHOEBUS_ROOT/lib/confirm.sh" -source "$PHOEBUS_ROOT/lib/install.sh" - -# A dry-run must never write to the configured install root. -config_set DRY_RUN "yes" -config_set TARGET_DISK "/dev/definitely-not-a-real-disk" -config_set INSTALL_ROOT "$STATE_DIR/host-root-should-stay-empty" -config_set USERNAME "tester" -install_effective_root >/dev/null -INSTALL_TARGET_ROOT="$(install_effective_root)" - -assert_success "dry-run storage stage" install_stage_storage -assert_success "sandbox root created" test -d "$INSTALL_TARGET_ROOT" -assert_failure "host install root untouched" test -e "$(config_get INSTALL_ROOT)" - -assert_success "dry-run base stage" install_stage_base -assert_success "dry-run portage stage" install_stage_portage - -# scripts created by later stages stay inside the sandbox -assert_success "dry-run kernel profile writes to sandbox" install_stage_kernel -assert_success "kernel fragment in sandbox" test -e "$INSTALL_TARGET_ROOT/etc/kernel/config.d/00-phoebus-profile.config" - -# preflight refuses an incomplete configuration (no real target disk) -config_set DRY_RUN "no" -assert_failure "preflight rejects incomplete config" install_preflight - -phoebus_test_report diff --git a/installer/tests/test_opencode.sh b/installer/tests/test_opencode.sh deleted file mode 100644 index 64a4e57..0000000 --- a/installer/tests/test_opencode.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_opencode" -phoebus_test_setup - -url="$(opencode_manifest_get x86_64 url)" -sha="$(opencode_manifest_get x86_64 sha256)" -assert_contains "$url" "opencode-linux-x64.tar.gz" "manifest has x86_64 url" -assert_eq "64" "${#sha}" "manifest sha256 is 64 hex chars" -assert_eq "v1.18.31" "$(opencode_version_manifest)" "manifest pins a version" - -# checksum verification -f="$STATE_DIR/artifact" -printf 'hello phoebus\n' >"$f" -good="$(sha256sum "$f" | awk '{print $1}')" -assert_success "correct checksum accepted" opencode_checksum_ok "$f" "$good" -assert_failure "wrong checksum rejected" opencode_checksum_ok "$f" "deadbeef" -assert_failure "placeholder checksum rejected" opencode_checksum_ok "$f" "0000000000000000000000000000000000000000000000000000000000000000" -assert_failure "empty checksum rejected" opencode_checksum_ok "$f" "" - -# unknown arch has no usable entry -assert_failure "unknown arch refused" opencode_manifest_get sparc url - -phoebus_test_report diff --git a/installer/tests/test_pkgpolicy.sh b/installer/tests/test_pkgpolicy.sh deleted file mode 100644 index 6a5f1ac..0000000 --- a/installer/tests/test_pkgpolicy.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_pkgpolicy" -phoebus_test_setup - -# Default is balanced and a binary source is configured. -config_set PACKAGE_POLICY "balanced" -config_set FEATURES_BINPKG "yes" -config_set BINHOST_URI "https://example.invalid/binpkgs" - -assert_eq "45" "$(pkgpolicy_compile_seconds app-editors/vim)" "known compile time (vim)" -assert_eq "300" "$(pkgpolicy_compile_seconds dev-libs/unknown)" "unknown defaults to 300s" - -assert_eq "source" "$(pkgpolicy_decide app-editors/vim)" "cheap package compiles" -assert_eq "binary" "$(pkgpolicy_decide www-client/firefox)" "huge package uses binary" -assert_eq "source" "$(pkgpolicy_decide sys-kernel/gentoo-kernel)" "kernel always compiles" - -# policy overrides -config_set PACKAGE_POLICY "source_first" -assert_eq "source" "$(pkgpolicy_decide www-client/firefox)" "source_first compiles everything" - -config_set PACKAGE_POLICY "binary_first" -assert_eq "binary" "$(pkgpolicy_decide app-editors/vim)" "binary_first prefers binaries" - -# history override -config_set PACKAGE_POLICY "balanced" -printf 'app-editors/vim\t7\t25\n' >"${STATE_DIR}/compile-times.tsv" -assert_eq "7" "$(pkgpolicy_compile_seconds app-editors/vim)" "history overrides estimate" - -# no binary host -> source even in binary_first -config_set BINHOST_URI "" -config_set PACKAGE_POLICY "binary_first" -assert_eq "source" "$(pkgpolicy_decide www-client/firefox)" "no binhost means compile" - -phoebus_test_report diff --git a/installer/tests/test_plan.sh b/installer/tests/test_plan.sh deleted file mode 100644 index cbfc473..0000000 --- a/installer/tests/test_plan.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_plan" -phoebus_test_setup - -config_set HOSTNAME "phoebus-test" -config_set USERNAME "tester" -config_set DESKTOP_PROFILE "dwl" -config_set PACKAGE_POLICY "balanced" - -plan_generate -plan="$(plan_render)" - -assert_contains "$plan" "Installation plan" "plan has header" -assert_contains "$plan" "phoebus-test" "plan includes hostname" -assert_contains "$plan" "tester" "plan includes username" -assert_contains "$plan" "dwl" "plan includes desktop profile" -assert_contains "$plan" "systemd" "plan includes init system" -assert_contains "$plan" "@snapshots" "plan includes snapshot subvolume" - -assert_eq "storage_prepare" "${PLAN_STEPS[0]}" "first step is storage_prepare" -assert_eq "finalize" "${PLAN_STEPS[${#PLAN_STEPS[@]}-1]}" "last step is finalize" - -# subvolume list is configurable -config_set BTRFS_SUBVOLS "@ @home @var @snapshots @swap @log" -plan_generate -assert_contains "$(plan_render)" "@log" "plan reflects configured subvolumes" - -# swap sizing is bounded -swap="$(plan_swap_mib)" -assert_success "swap size is numeric" test "$swap" -ge 1024 - -phoebus_test_report diff --git a/installer/tests/test_regressions.sh b/installer/tests/test_regressions.sh deleted file mode 100644 index 21bb543..0000000 --- a/installer/tests/test_regressions.sh +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Regression tests for bugs found during the first real VM installation. -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_regressions" -phoebus_test_setup - -# --- kernel cmdline: encrypted root must use rd.luks.name== ----- -config_set ENCRYPTION "luks2" -config_set LUKS_NAME "cryptroot" -FS_ROOT_PART="/dev/fake" -blkid() { printf '%s\n' "00000000-1111-2222-3333-444444444444"; } -root="$STATE_DIR/target" -mkdir -p "$root" -kernel_write_cmdline "$root" -cmdline="$(cat "$root/etc/kernel/cmdline")" -assert_contains "$cmdline" "rd.luks.name=00000000-1111-2222-3333-444444444444=cryptroot" \ - "cmdline names the LUKS mapper" -assert_contains "$cmdline" "root=/dev/mapper/cryptroot" "cmdline root is the mapper" -assert_not_contains "$cmdline" "rd.luks.uuid=" "cmdline does not use un-named rd.luks.uuid" - -# --- install.conf must declare every generator (it replaces the default) ---- -boot_write_install_conf "$root" -iconf="$(cat "$root/etc/kernel/install.conf")" -assert_contains "$iconf" "layout=bls" "install.conf uses BLS layout" -assert_contains "$iconf" "initrd_generator=dracut" "install.conf sets initrd generator" -assert_contains "$iconf" "uki_generator=none" "install.conf disables UKI for BLS" - -# dracut must be forced to include crypt/btrfs for the encrypted root -boot_write_dracut_conf "$root" -dconf="$(cat "$root/etc/dracut.conf.d/10-phoebus.conf")" -assert_contains "$dconf" "add_dracutmodules" "dracut config adds modules" -assert_contains "$dconf" "crypt" "dracut includes crypt" -assert_contains "$dconf" "btrfs" "dracut includes btrfs" - -# --- fstab must be generated after the stage3 extraction -------------------- -plan_generate -sig="" fgi="" pci="" -for i in "${!PLAN_STEPS[@]}"; do - case "${PLAN_STEPS[$i]}" in - stage_install) sig="$i" ;; - fstab_generate) fgi="$i" ;; - portage_configure) pci="$i" ;; - esac -done -assert_success "fstab_generate is a plan step" test -n "$fgi" -assert_success "stage_install precedes fstab_generate" test "$sig" -lt "$fgi" -assert_success "fstab_generate precedes portage_configure" test "$fgi" -lt "$pci" - -__fn_contains() { declare -f "$1" | grep -q "$2"; } -assert_failure "storage stage does not generate fstab" \ - __fn_contains install_stage_storage filesystem_generate_fstab -assert_success "fstab stage generates fstab" \ - __fn_contains install_stage_fstab filesystem_generate_fstab -assert_success "fstab stage creates /var/tmp" \ - __fn_contains install_stage_fstab "/var/tmp" - -# --- chroot commands set TMPDIR (systemd kernel-install requires it) -------- -assert_success "portage_chroot sets TMPDIR" \ - __fn_contains portage_chroot "TMPDIR=/tmp" -assert_success "portage_chroot_stdin sets TMPDIR" \ - __fn_contains portage_chroot_stdin "TMPDIR=/tmp" - -# --- initial cmdline includes the configured console ------------------------ -config_set KERNEL_CONSOLE "console=tty0 console=ttyS0,115200" -kernel_write_cmdline "$root" -assert_contains "$(cat "$root/etc/kernel/cmdline")" "console=ttyS0,115200" \ - "cmdline includes configured console" -config_set KERNEL_CONSOLE "console=tty0" - -# --- base packages must include the storage userspace needed by dracut ------ -basepkgs="$(portage_base_packages)" -assert_contains "$basepkgs" "sys-fs/cryptsetup" "base packages include cryptsetup" -assert_contains "$basepkgs" "sys-fs/btrfs-progs" "base packages include btrfs-progs" - -# --- systemd must be built with cryptsetup for the initramfs --------------- -pkgroot="$STATE_DIR/pkgroot" -mkdir -p "$pkgroot/etc/portage" -config_set DESKTOP_PROFILE "dwl" -portage_write_package_files "$pkgroot" -pupkg="$(cat "$pkgroot/etc/portage/package.use/phoebus")" -assert_contains "$pupkg" "sys-apps/systemd boot policykit cryptsetup" \ - "systemd built with boot/policykit/cryptsetup" -assert_contains "$pupkg" "sys-kernel/installkernel" "installkernel policy present" -assert_contains "$pupkg" "x11-libs/cairo X" "desktop enables cairo X for GTK3" -config_set DESKTOP_PROFILE "none" - -# --- fstab must mount @swap so the swapfile can be activated ---------------- -FS_EFI_PART="/dev/fake-efi" -FS_ROOT_SOURCE="/dev/fake-root" -mkdir -p "$root/etc" -filesystem_generate_fstab "$root" -fstab="$(cat "$root/etc/fstab")" -assert_contains "$fstab" "subvol=@swap" "fstab mounts @swap subvolume" -assert_contains "$fstab" "/swap/swapfile" "fstab enables the swapfile" - -# --- secrets never reach the log ------------------------------------------- -secret_register "topsecretvalue123" -run_cmd "secret test" /bin/true "topsecretvalue123" >/dev/null 2>&1 -logtext="$(cat "$PHOEBUS_LOG_FILE")" -assert_not_contains "$logtext" "topsecretvalue123" "secret is scrubbed from the log" - -phoebus_test_report diff --git a/installer/tests/test_safety.sh b/installer/tests/test_safety.sh deleted file mode 100644 index 88020c3..0000000 --- a/installer/tests/test_safety.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_safety" -phoebus_test_setup -# confirm.sh and install.sh are not loaded by lib.sh; load them explicitly. -source "$PHOEBUS_ROOT/lib/confirm.sh" -source "$PHOEBUS_ROOT/lib/install.sh" - -# destructive commands are blocked until authorized -destructive_revoke -assert_failure "run_destructive blocked when unauthorized" run_destructive "test op" true - -# after authorization, dry-run still prevents execution -config_set DRY_RUN "yes" -destructive_grant -assert_success "run_destructive allowed after grant (dry-run)" run_destructive "test op" /bin/true -destructive_revoke - -# effective root is a sandbox in dry-run, never the configured target -config_set INSTALL_ROOT "/mnt/do-not-touch" -config_set DRY_RUN "yes" -root="$(install_effective_root)" -assert_neq "/mnt/do-not-touch" "$root" "dry-run uses a sandbox root" -assert_contains "$root" "dry-run-root" "sandbox root name is explicit" - -# in a real run the configured root is used -config_set DRY_RUN "no" -assert_eq "/mnt/do-not-touch" "$(install_effective_root)" "real root used when not dry-run" - -phoebus_test_report diff --git a/installer/tests/test_state.sh b/installer/tests/test_state.sh deleted file mode 100644 index 3f44747..0000000 --- a/installer/tests/test_state.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_state" -phoebus_test_setup - -assert_eq "phoebus" "$(config_get HOSTNAME)" "default hostname" - -config_set HOSTNAME "testbox" -assert_eq "testbox" "$(config_get HOSTNAME)" "config_set updates value" - -config_default HOSTNAME "should-not-apply" -assert_eq "testbox" "$(config_get HOSTNAME)" "config_default does not override" - -config_set SECRET_KEY "s3cr3t" -config_set USERNAME "alice" - -local_file="$STATE_DIR/state.conf" -config_save_file "$local_file" -assert_success "config file written" test -s "$local_file" - -config_set HOSTNAME "changed" -config_load_file "$local_file" -assert_eq "testbox" "$(config_get HOSTNAME)" "round-trip restores value" -assert_eq "alice" "$(config_get USERNAME)" "round-trip restores username" - -assert_not_contains "$(cat "$local_file")" "PASSWORD" "secret keys with PASSWORD are not saved" - -# redaction -secret_register "hunter2" -secret_register "topsecret" -assert_eq "pw=" "$(redact_scrub "pw=hunter2")" "registered secret is scrubbed" -assert_eq "x" "$(redact_scrub "x")" "normal text unchanged" -assert_eq "" "$(redact_value USER_PASSWORD "abc")" "redact_value hides password" -assert_eq "abc" "$(redact_value HOSTNAME "abc")" "redact_value keeps non-secret" - -phoebus_test_report diff --git a/installer/tests/test_syntax.sh b/installer/tests/test_syntax.sh deleted file mode 100644 index 17f0dff..0000000 --- a/installer/tests/test_syntax.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_syntax" -PHOEBUS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" - -failures=0 -count=0 -while IFS= read -r file; do - count=$((count + 1)) - if bash -n "$file" 2>/dev/null; then - printf ' ok syntax %s\n' "${file#"$PHOEBUS_ROOT"/}" - else - printf ' FAIL syntax %s\n' "${file#"$PHOEBUS_ROOT"/}" - bash -n "$file" 2>&1 | sed 's/^/ /' - failures=$((failures + 1)) - fi -done < <(find "$PHOEBUS_ROOT" -type f \( -name '*.sh' -o -path '*/bin/*' \) | sort) - -TESTS_RUN=$count -TESTS_FAILED=$failures -phoebus_test_report diff --git a/installer/tests/test_validation.sh b/installer/tests/test_validation.sh deleted file mode 100644 index 2fc34e8..0000000 --- a/installer/tests/test_validation.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" -TEST_NAME="test_validation" -phoebus_test_setup - -assert_success "valid hostname" validate_hostname "phoebus" -assert_success "hostname with hyphen" validate_hostname "my-box" -assert_failure "hostname with space" validate_hostname "bad host" -assert_failure "empty hostname" validate_hostname "" -assert_failure "hostname leading -" validate_hostname "-bad" - -assert_success "valid username" validate_username "alice" -assert_failure "root refused" validate_username "root" -assert_failure "uppercase username" validate_username "Alice" -assert_failure "empty username" validate_username "" - -assert_success "valid timezone" validate_timezone "UTC" -assert_failure "empty timezone" validate_timezone "" - -assert_failure "target not a block device" validate_target_disk "/dev/does-not-exist-xyz" -assert_failure "empty target" validate_target_disk "" - -assert_success "sr0 protected" disks_is_protected "/dev/sr0" -assert_success "loop protected" disks_is_protected "/dev/loop0" - -assert_eq "weak" "$(validate_password_strength "abc")" "short password weak" -assert_eq "weak" "$(validate_password_strength "abcdefghij")" "10 lowercase chars weak" -assert_eq "fair" "$(validate_password_strength "Abcdefghij")" "mixed-case password fair" -assert_eq "strong" "$(validate_password_strength "Abcdef1!ghijk")" "complex password strong" - -# validate_config reports missing required fields -config_set HOSTNAME "ok-host" -config_set USERNAME "" -problems="$(validate_config HOSTNAME USERNAME)" -assert_contains "$problems" "username" "validate_config flags missing username" - -phoebus_test_report diff --git a/installer/tui/menu.sh b/installer/tui/menu.sh deleted file mode 100644 index 3c9516c..0000000 --- a/installer/tui/menu.sh +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Main menu and review/install flow. - -# _status_line - short right-hand column value for menu entries -_menu_items() { - printf '%s\n' \ - keyboard "Keyboard [$(config_get KEYMAP)]" \ - network "Network [$(network_online && echo online || echo offline)]" \ - source "Source [$(config_get STAGE3_URL)]" \ - hostname "Hostname [$(config_get HOSTNAME)]" \ - locale "Locale [$(config_get LOCALE)]" \ - timezone "Timezone [$(config_get TIMEZONE)]" \ - user "User [$(config_get USERNAME)]" \ - disk "Disk [$(config_get TARGET_DISK)]" \ - filesystem "Filesystem[$(config_get FILESYSTEM)/$(config_get ENCRYPTION)]" \ - boot "Boot [$(config_get BOOTLOADER)]" \ - kernel "Kernel [$(config_get KERNEL_PROFILE)]" \ - packages "Packages [$(config_get PACKAGE_POLICY)]" \ - desktop "Desktop [$(config_get DESKTOP_PROFILE)]" \ - ai "AI [$(opencode_available && echo ready || echo not-installed)]" \ - review "Review configuration" \ - install "Install" \ - exit "Exit" -} - -# menu_review - show the full plan and validation status -menu_review() { - local tmp rc - plan_generate - tmp="$(mktemp)" - { - plan_render - printf '\n\nValidation\n==========\n' - local problems - problems="$(validate_config)" - if [[ -z "$problems" ]]; then - printf 'Configuration looks complete.\n' - else - printf '%s\n' "$problems" | sed 's/^/- /' - fi - printf '\n\nPackage policy examples\n=======================\n' - pkgpolicy_report - } >"$tmp" - ui_textbox "Review configuration" "$tmp" - rc=$? - rm -f "$tmp" - if ui_yesno "Review configuration" "Save this configuration to a file?"; then - local dest="/root/phoebus-install.conf" - config_save_file "$dest" && ui_msgbox "Saved" "Configuration saved to $dest" - fi - return $rc -} - -# menu_install - the guarded, destructive path -menu_install() { - local problems preview - problems="$(validate_config)" - if [[ -n "$problems" ]]; then - ui_error "Configuration is incomplete: - -$problems" - return 1 - fi - - plan_generate - local tmp - tmp="$(mktemp)" - plan_render >"$tmp" - ui_textbox "Installation plan" "$tmp" - rm -f "$tmp" - - if config_bool DRY_RUN; then - ui_msgbox "Dry run" "Dry-run mode is enabled. - -No disk will be modified. Commands are only logged." - fi - - preview="$(plan_destructive_preview)" - if ! confirm_erase "$preview"; then - log_info "installation cancelled at ERASE confirmation" - ui_msgbox "Cancelled" "Installation cancelled. No changes were made." - return 1 - fi - if ! confirm_action "Start the installation now? This can take a long time."; then - log_info "installation cancelled at final confirmation" - ui_msgbox "Cancelled" "Installation cancelled. No changes were made." - return 1 - fi - - destructive_grant - (ui_infobox "Installing" "Installation in progress. Please wait...") 2>/dev/null || true - local rc=0 - install_run || rc=$? - destructive_revoke - - if ((rc == 0)); then - if config_bool DRY_RUN; then - ui_msgbox "Dry run complete" "The plan executed in dry-run mode. - -Log: $PHOEBUS_LOG_FILE" - else - ui_msgbox "Installation complete" "Installation finished successfully. - -Log: $PHOEBUS_LOG_FILE - -You can now reboot into $(config_get DISTRO_NAME)." - fi - return 0 - fi - - ui_error "Installation failed during stage: ${INSTALL_FAILED_STAGE:-unknown}" - if ui_yesno "Installation failed" "Show the last 60 log lines?"; then - tmp="$(mktemp)" - log_tail 60 >"$tmp" - ui_textbox "Installer log" "$tmp" - rm -f "$tmp" - fi - return 1 -} - -# menu_main - the top-level loop -menu_main() { - local choice - while true; do - local -a items=() - mapfile -t items < <(_menu_items) - if ! ui_menu "Main menu" "Configure the installation, then choose Install. - -Settings can be revisited at any time before installing." \ - 24 78 17 "${items[@]}"; then - if ui_yesno "Exit" "Exit the installer?"; then - return 0 - fi - continue - fi - choice="$UI_RESULT" - case "$choice" in - keyboard) screen_keyboard ;; - network) screen_network ;; - source) screen_source ;; - hostname) screen_hostname ;; - locale) screen_locale ;; - timezone) screen_timezone ;; - user) screen_user ;; - disk) screen_disk ;; - filesystem) screen_filesystem ;; - boot) screen_boot ;; - kernel) screen_kernel ;; - packages) screen_packages ;; - desktop) screen_desktop ;; - ai) screen_ai ;; - review) menu_review ;; - install) menu_install ;; - exit) - if ui_yesno "Exit" "Exit the installer?"; then - return 0 - fi ;; - esac - done -} diff --git a/installer/tui/screens.sh b/installer/tui/screens.sh deleted file mode 100644 index 4d67c99..0000000 --- a/installer/tui/screens.sh +++ /dev/null @@ -1,463 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Configuration screens for the main menu. -# -# Each screen edits the structured configuration (CFG). Screens can be revisited -# at any time before installation; nothing here touches a disk. - -_ui_ok() { return 0; } - -# _pick_from_list TITLE TEXT CANDIDATES... - radiolist, sets UI_RESULT -_pick_from_list() { - local title="$1" text="$2" current="$3"; shift 3 - local -a items=() item - for item in "$@"; do - if [[ "$item" == "$current" ]]; then - items+=("$item" "" on) - else - items+=("$item" "" off) - fi - done - ui_radiolist "$title" "$text" 0 0 12 "${items[@]}" -} - -# --------------------------------------------------------------------------- -# 1. Keyboard -# --------------------------------------------------------------------------- -screen_keyboard() { - local current choice custom - current="$(config_get KEYMAP)" - local -a layouts=(us gb de fr es it pt-br dvorak colemak ru pl nl se no dk "fi" cz hu tr jp kr) - if _pick_from_list "Keyboard" "Select a console keymap:" "$current" "${layouts[@]}" other; then - choice="$UI_RESULT" - else - return 0 - fi - if [[ "$choice" == "other" ]]; then - ui_inputbox "Keyboard" "Enter a keymap name (e.g. us-acentos):" "$current" || return 0 - custom="$UI_RESULT" - [[ -n "$custom" ]] && config_set KEYMAP "$custom" - else - config_set KEYMAP "$choice" - fi -} - -# --------------------------------------------------------------------------- -# 2. Network -# --------------------------------------------------------------------------- -screen_network() { - local status action - network_live_start - status="$(network_status_text)" - while true; do - if ! ui_menu "Network" "$status - -Choose an action:" 18 70 5 \ - status "Show interface status" \ - wifi "Connect to a Wi-Fi network" \ - refresh "Refresh status" \ - "done" "Back"; then - return 0 - fi - action="$UI_RESULT" - case "$action" in - status|refresh) status="$(network_status_text)" ;; - wifi) - local scan - scan="$(network_wifi_scan)" - if [[ -z "$scan" ]]; then - ui_msgbox "Network" "No Wi-Fi networks found. You can configure networking later." - continue - fi - local tmp - tmp="$(mktemp)" - printf '%s\n' "$scan" >"$tmp" - local -a items=() - local ssid sig sec - while read -r ssid sig sec; do - [[ -z "$ssid" ]] && continue - items+=("$ssid" "${sig} ${sec}" off) - done <"$tmp" - rm -f "$tmp" - ((${#items[@]})) || continue - if ui_radiolist "Wi-Fi" "Select a network:" 0 0 12 "${items[@]}"; then - ssid="$UI_RESULT" - ui_passwordbox "Wi-Fi" "Passphrase for '$ssid' (blank for open):" || continue - network_connect_wifi "$ssid" "$UI_RESULT" || ui_error "Could not connect to $ssid" - fi - ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 3. Source / installation media -# --------------------------------------------------------------------------- -screen_source() { - local url sha - while true; do - if ! ui_menu "Source" "Stage3 source - -Mirror: $(config_get STAGE3_MIRROR) -URL: $(config_get STAGE3_URL) -SHA-256: $(config_get STAGE3_SHA256)" 16 74 4 \ - auto "Use current stable systemd stage3" \ - pin "Pin an explicit stage3 URL" \ - sha "Set expected SHA-256" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - auto) config_set STAGE3_URL ""; config_set STAGE3_SHA256 "" ;; - pin) - ui_inputbox "Source" "Stage3 tarball URL:" "$(config_get STAGE3_URL)" || continue - config_set STAGE3_URL "$UI_RESULT" ;; - sha) - ui_inputbox "Source" "Expected SHA-256 (blank to clear):" "$(config_get STAGE3_SHA256)" || continue - config_set STAGE3_SHA256 "$UI_RESULT" ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 4. Hostname -# --------------------------------------------------------------------------- -screen_hostname() { - local hostname - ui_inputbox "Hostname" "Enter the system hostname:" "$(config_get HOSTNAME)" || return 0 - hostname="$UI_RESULT" - if validate_hostname "$hostname" >/dev/null; then - config_set HOSTNAME "$hostname" - else - ui_error "$(validate_hostname "$hostname")" - fi -} - -# --------------------------------------------------------------------------- -# 5. Locale -# --------------------------------------------------------------------------- -screen_locale() { - local current - current="$(config_get LOCALE)" - local -a locales=(en_US.UTF-8 en_GB.UTF-8 de_DE.UTF-8 fr_FR.UTF-8 es_ES.UTF-8 it_IT.UTF-8 pt_BR.UTF-8 nl_NL.UTF-8 pl_PL.UTF-8 ru_RU.UTF-8) - if _pick_from_list "Locale" "Select the system locale:" "$current" "${locales[@]}" other; then - if [[ "$UI_RESULT" == "other" ]]; then - ui_inputbox "Locale" "Enter a locale (e.g. sv_SE.UTF-8):" "$current" || return 0 - [[ -n "$UI_RESULT" ]] && config_set LOCALE "$UI_RESULT" - else - config_set LOCALE "$UI_RESULT" - fi - fi -} - -# --------------------------------------------------------------------------- -# 6. Timezone -# --------------------------------------------------------------------------- -screen_timezone() { - local current - current="$(config_get TIMEZONE)" - local -a zones=(UTC Europe/London Europe/Berlin Europe/Paris Europe/Madrid Europe/Rome Europe/Amsterdam Europe/Warsaw America/New_York America/Chicago America/Denver America/Los_Angeles America/Sao_Paulo Asia/Tokyo Asia/Shanghai Asia/Kolkata Australia/Sydney) - if _pick_from_list "Timezone" "Select the timezone:" "$current" "${zones[@]}" other; then - if [[ "$UI_RESULT" == "other" ]]; then - ui_inputbox "Timezone" "Enter a timezone (e.g. Europe/Stockholm):" "$current" || return 0 - [[ -n "$UI_RESULT" ]] && config_set TIMEZONE "$UI_RESULT" - else - config_set TIMEZONE "$UI_RESULT" - fi - fi -} - -# --------------------------------------------------------------------------- -# 7. User account -# --------------------------------------------------------------------------- -screen_user() { - local username fullname - while true; do - if ! ui_menu "User account" "Username: $(config_get USERNAME) -Full name: $(config_get USER_FULLNAME) -Groups: $(config_get USER_GROUPS)" 15 74 4 \ - username "Set username" \ - fullname "Set full name" \ - password "Set password" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - username) - ui_inputbox "User account" "Username:" "$(config_get USERNAME)" || continue - username="$UI_RESULT" - if validate_username "$username" >/dev/null; then - config_set USERNAME "$username" - else - ui_error "$(validate_username "$username")" - fi - ;; - fullname) - ui_inputbox "User account" "Full name:" "$(config_get USER_FULLNAME)" || continue - config_set USER_FULLNAME "$UI_RESULT" ;; - password) - users_prompt_passwords || ui_error "Could not set password" - ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 8. Disk -# --------------------------------------------------------------------------- -screen_disk() { - local current disk reason - current="$(config_get TARGET_DISK)" - disks_refresh - if ((${#DISK_LIST[@]} == 0)); then - ui_error "No disks were detected." - return 0 - fi - local -a items=() - for disk in "${DISK_LIST[@]}"; do - reason="$(disk_protected_reason "$disk")" - if [[ -n "$reason" ]]; then - continue - fi - if [[ "$disk" == "$current" ]]; then - items+=("$disk" "$(disk_display_line "$disk")" on) - else - items+=("$disk" "$(disk_display_line "$disk")" off) - fi - done - if ((${#items[@]} == 0)); then - ui_error "No safe target disks found. All detected disks are protected (live medium, mounted, or read-only)." - return 0 - fi - if ui_radiolist "Disk" "Select the installation target. - -All data on the selected disk will be destroyed later, after review." \ - 0 0 10 "${items[@]}"; then - config_set TARGET_DISK "$UI_RESULT" - local tmp - tmp="$(mktemp)" - disk_layout_text "$UI_RESULT" >"$tmp" 2>/dev/null - ui_textbox "Current layout: $UI_RESULT" "$tmp" - rm -f "$tmp" - fi -} - -# --------------------------------------------------------------------------- -# 9. Filesystem / encryption -# --------------------------------------------------------------------------- -screen_filesystem() { - local action - while true; do - if ! ui_menu "Filesystem" "Filesystem: $(config_get FILESYSTEM) -Encryption: $(config_get ENCRYPTION) -Compression: $(config_get COMPRESS) -EFI size: $(config_get EFI_SIZE_MIB) MiB" 17 74 6 \ - fs "Change filesystem" \ - encryption "Change encryption" \ - passphrase "Set encryption passphrase" \ - compress "Change Btrfs compression" \ - efi "Change EFI partition size" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - fs) - if _pick_from_list "Filesystem" "Select the root filesystem:" "$(config_get FILESYSTEM)" btrfs ext4; then - config_set FILESYSTEM "$UI_RESULT" - fi ;; - encryption) - if _pick_from_list "Encryption" "Select encryption for the root partition:" "$(config_get ENCRYPTION)" luks2 none; then - config_set ENCRYPTION "$UI_RESULT" - fi ;; - passphrase) - encryption_configure || ui_error "Passphrase not set" ;; - compress) - ui_inputbox "Filesystem" "Btrfs compression (zstd:3 recommended):" "$(config_get COMPRESS)" || continue - config_set COMPRESS "$UI_RESULT" ;; - efi) - ui_inputbox "Filesystem" "EFI partition size in MiB:" "$(config_get EFI_SIZE_MIB)" || continue - [[ "$UI_RESULT" =~ ^[0-9]+$ ]] && config_set EFI_SIZE_MIB "$UI_RESULT" ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 10. Boot -# --------------------------------------------------------------------------- -screen_boot() { - local action - while true; do - if ! ui_menu "Boot" "Bootloader: $(config_get BOOTLOADER) -Unified UKI: $(config_get KERNEL_UKI) -Secure Boot: $(config_get SECUREBOOT) -Keep kernels: $(config_get KEEP_KERNELS) - -Secure Boot status: $(boot_secureboot_status)" 18 74 4 \ - uki "Toggle Unified Kernel Image" \ - keep "Set number of kernels to keep" \ - secure "Toggle Secure Boot preference (not enforced yet)" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - uki) - if config_bool KERNEL_UKI; then config_set KERNEL_UKI no; else config_set KERNEL_UKI yes; fi ;; - keep) - ui_inputbox "Boot" "Number of kernels to keep (>=2):" "$(config_get KEEP_KERNELS)" || continue - if [[ "$UI_RESULT" =~ ^[0-9]+$ ]] && ((UI_RESULT >= 2)); then - config_set KEEP_KERNELS "$UI_RESULT" - else - ui_error "Keep at least 2 kernels so a known-good kernel is always available." - fi ;; - secure) - if config_bool SECUREBOOT; then config_set SECUREBOOT no; else config_set SECUREBOOT yes; fi ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 11. Kernel -# --------------------------------------------------------------------------- -screen_kernel() { - local action - while true; do - if ! ui_menu "Kernel" "Profile: $(config_get KERNEL_PROFILE) -Package: $(kernel_select_package) -UKI: $(config_get KERNEL_UKI) - -Recommended for this machine: $(hw_recommended_kernel_profile)" 17 74 4 \ - profile "Select kernel profile" \ - package "Select kernel package" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - profile) - if _pick_from_list "Kernel" "safe = prebuilt distribution kernel -optimized = distribution kernel, conservative local fragments (default) -aggressive = distribution sources with a locally tuned config" \ - "$(config_get KERNEL_PROFILE)" safe optimized aggressive; then - config_set KERNEL_PROFILE "$UI_RESULT" - fi ;; - package) - ui_inputbox "Kernel" "Kernel package:" "$(config_get KERNEL_PACKAGE)" || continue - config_set KERNEL_PACKAGE "$UI_RESULT" ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 12. Package policy -# --------------------------------------------------------------------------- -screen_packages() { - local action - while true; do - if ! ui_menu "Packages" "Policy: $(config_get PACKAGE_POLICY) -Binary packages: $(config_get FEATURES_BINPKG) -Accept license: $(config_get ACCEPT_LICENSE) - -source_first - compile everything possible -balanced - compile cheap/frequent, use binaries for huge packages (default) -binary_first - prefer binaries whenever available" 19 76 5 \ - policy "Change policy" \ - binpkg "Toggle binary packages" \ - license "Change accepted licenses" \ - show "Show example decisions" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - policy) - if _pick_from_list "Packages" "Select the package policy:" "$(config_get PACKAGE_POLICY)" source_first balanced binary_first; then - config_set PACKAGE_POLICY "$UI_RESULT" - fi ;; - binpkg) - if config_bool FEATURES_BINPKG; then config_set FEATURES_BINPKG no; else config_set FEATURES_BINPKG yes; fi ;; - license) - ui_inputbox "Packages" "ACCEPT_LICENSE value:" "$(config_get ACCEPT_LICENSE)" || continue - config_set ACCEPT_LICENSE "$UI_RESULT" ;; - show) - local tmp - tmp="$(mktemp)" - pkgpolicy_report >"$tmp" - ui_textbox "Package policy examples" "$tmp" - rm -f "$tmp" ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 13. Desktop -# --------------------------------------------------------------------------- -screen_desktop() { - local action - while true; do - if ! ui_menu "Desktop" "Profile: $(config_get DESKTOP_PROFILE) -Flatpak: $(config_get FLATPAK) -Audio: $(config_get AUDIO_STACK) - -none - server / no graphical session -minimal - Wayland libraries and XWayland only -dwl - dwl tiling desktop with Waybar, fuzzel, mako, ... -full - dwl plus Flatpak, BlueZ and keyring" 20 76 5 \ - profile "Select desktop profile" \ - flatpak "Toggle Flatpak" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - profile) - if _pick_from_list "Desktop" "Select the desktop profile:" "$(config_get DESKTOP_PROFILE)" none minimal dwl full; then - config_set DESKTOP_PROFILE "$UI_RESULT" - fi ;; - flatpak) - if config_bool FLATPAK; then config_set FLATPAK no; else config_set FLATPAK yes; fi ;; - done) return 0 ;; - esac - done -} - -# --------------------------------------------------------------------------- -# 14. AI configuration -# --------------------------------------------------------------------------- -screen_ai() { - local action - while true; do - if ! ui_menu "AI assistant" "$(ai_status_text)" 18 76 4 \ - configure "Configure provider and model" \ - bootstrap "Install / verify OpenCode" \ - test "Test OpenCode availability" \ - "done" "Back"; then - return 0 - fi - case "$UI_RESULT" in - configure) ai_configure ;; - bootstrap) - if opencode_bootstrap; then - ui_msgbox "AI assistant" "OpenCode installed and verified." - else - ui_error "OpenCode installation failed. See the log for details." - fi ;; - test) - if opencode_available; then - local bin ver - bin="$(opencode_detect)" - ver="$(opencode_print_version "$bin")" - ui_msgbox "AI assistant" "OpenCode found: -$bin -version: ${ver:-unknown}" - else - ui_msgbox "AI assistant" "OpenCode is not installed. Use 'Install / verify OpenCode'." - fi ;; - done) return 0 ;; - esac - done -} diff --git a/installer/tui/ui.sh b/installer/tui/ui.sh deleted file mode 100644 index c6edfb3..0000000 --- a/installer/tui/ui.sh +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env bash -# shellcheck shell=bash -# -# Thin TUI wrapper around dialog/whiptail. -# -# dialog is the preferred backend (present in the Gentoo LiveGUI reference). -# whiptail is accepted as a fallback so the installer also works in minimal -# environments. Only the common option subset is used. -# -# All functions store the result in UI_RESULT and return 0 on OK / 1 on cancel. - -declare -g UI_BACKEND="${UI_BACKEND:-auto}" -declare -g UI_RESULT="${UI_RESULT:-}" -declare -g UI_TITLE="${UI_TITLE:-}" - -ui_init() { - if [[ "$UI_BACKEND" == "auto" ]]; then - if command -v dialog >/dev/null 2>&1; then - UI_BACKEND="dialog" - elif command -v whiptail >/dev/null 2>&1; then - UI_BACKEND="whiptail" - else - UI_BACKEND="none" - fi - fi - UI_TITLE="${DISTRO_NAME:-Phoebus OS} Installer" - [[ "$UI_BACKEND" == "none" ]] && return 1 - return 0 -} - -ui_available() { [[ "$UI_BACKEND" != "none" ]]; } - -_ui() { - case "$UI_BACKEND" in - dialog) dialog "$@" ;; - whiptail) whiptail "$@" ;; - *) return 127 ;; - esac -} - -# _ui_capture ARGS... - run and put textual result in UI_RESULT -_ui_capture() { - local f rc - f="$(mktemp "${TMPDIR:-/tmp}/phoebus-ui.XXXXXX")" || return 1 - _ui --output-fd 3 "$@" 3>"$f" - rc=$? - UI_RESULT="$(cat "$f")" - rm -f "$f" - case "$rc" in - 0) return 0 ;; - *) return 1 ;; - esac -} - -ui_backtitle_args() { - printf '%s\n' --backtitle "$UI_TITLE" -} - -ui_msgbox() { - local title="$1" text="$2" - _ui --title "$title" --backtitle "$UI_TITLE" --msgbox "$text" 0 0 -} - -ui_yesno() { - local title="$1" text="$2" - _ui --title "$title" --backtitle "$UI_TITLE" --yesno "$text" 0 0 -} - -ui_inputbox() { - local title="$1" text="$2" init="${3-}" - _ui_capture --title "$title" --backtitle "$UI_TITLE" --inputbox "$text" 0 0 "$init" -} - -ui_passwordbox() { - local title="$1" text="$2" - if [[ "$UI_BACKEND" == "dialog" ]]; then - _ui_capture --title "$title" --backtitle "$UI_TITLE" --insecure --passwordbox "$text" 0 0 - else - _ui_capture --title "$title" --backtitle "$UI_TITLE" --passwordbox "$text" 0 0 - fi -} - -ui_menu() { - local title="$1" text="$2" height="$3" width="$4" listheight="$5" - shift 5 - _ui_capture --title "$title" --backtitle "$UI_TITLE" \ - --menu "$text" "$height" "$width" "$listheight" "$@" -} - -ui_radiolist() { - local title="$1" text="$2" height="$3" width="$4" listheight="$5" - shift 5 - _ui_capture --title "$title" --backtitle "$UI_TITLE" \ - --radiolist "$text" "$height" "$width" "$listheight" "$@" -} - -ui_checklist() { - local title="$1" text="$2" height="$3" width="$4" listheight="$5" - shift 5 - _ui_capture --title "$title" --backtitle "$UI_TITLE" \ - --checklist "$text" "$height" "$width" "$listheight" "$@" -} - -ui_textbox() { - local title="$1" file="$2" - _ui --title "$title" --backtitle "$UI_TITLE" --textbox "$file" 0 0 -} - -ui_infobox() { - local title="$1" text="$2" - _ui --title "$title" --backtitle "$UI_TITLE" --infobox "$text" 0 0 - return 0 -} - -# ui_pause - wait for the user to acknowledge a message -ui_pause() { - ui_msgbox "${1:-Information}" "${2:-Press OK to continue.}" -} - -# ui_error - show an error with the log location -ui_error() { - local message="$1" - ui_msgbox "Error" "$message - -See the log for details: -$PHOEBUS_LOG_FILE" -}