//! Structured, strongly-typed installation configuration. //! //! Closed sets (filesystem, encryption, bootloader, kernel profile, package //! policy, desktop profile) are enums. Free-form values (hostname, locale, //! timezone, ...) are validated by `validate::validate`. //! //! Two input formats are supported during the Bash -> Rust migration: //! * TOML (the native format) //! * the legacy flat `KEY='value'` format used by the Bash prototype //! //! Secrets are never part of this structure. use std::path::{Path, PathBuf}; use std::str::FromStr; use serde::{Deserialize, Deserializer, Serialize}; use crate::error::{CoreError, Result}; // --------------------------------------------------------------------------- // Closed enums // --------------------------------------------------------------------------- macro_rules! string_enum { ($name:ident { $($variant:ident => $text:literal),+ $(,)? }) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum $name { $(#[serde(rename = $text)] $variant),+ } impl $name { pub fn as_str(self) -> &'static str { match self { $(Self::$variant => $text),+ } } } impl std::fmt::Display for $name { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } impl FromStr for $name { type Err = CoreError; fn from_str(s: &str) -> Result { match s { $($text => Ok(Self::$variant),)+ other => Err(CoreError::UnknownValue { field: stringify!($name), value: other.to_string(), }), } } } }; } string_enum!(Filesystem { Btrfs => "btrfs", Ext4 => "ext4" }); string_enum!(Encryption { None => "none", Luks2 => "luks2" }); string_enum!(Bootloader { SystemdBoot => "systemd-boot" }); string_enum!(KernelProfile { Safe => "safe", Optimized => "optimized", Aggressive => "aggressive" }); string_enum!(PackagePolicy { Balanced => "balanced", SourceFirst => "source_first", BinaryFirst => "binary_first" }); string_enum!(DesktopProfile { None => "none", Minimal => "minimal", Dwl => "dwl", Full => "full" }); impl Bootloader { pub fn default_systemd_boot() -> Self { Bootloader::SystemdBoot } } // --------------------------------------------------------------------------- // serde helper: accept either a string or a sequence of strings // --------------------------------------------------------------------------- fn de_string_or_seq<'de, D>(deserializer: D) -> std::result::Result, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(untagged)] enum StringOrVec { One(String), Many(Vec), } let value = StringOrVec::deserialize(deserializer)?; Ok(match value { StringOrVec::One(s) => split_list(&s), StringOrVec::Many(v) => v, }) } /// Split a whitespace- or comma-separated list, dropping empty items. pub fn split_list(s: &str) -> Vec { s.split(|c: char| c.is_whitespace() || c == ',') .map(str::trim) .filter(|s| !s.is_empty()) .map(str::to_string) .collect() } // --------------------------------------------------------------------------- // Sections // --------------------------------------------------------------------------- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct SystemConfig { pub distro_name: String, pub distro_id: String, pub arch: String, pub hostname: String, pub keymap: String, pub locale: String, pub timezone: String, pub root_shell: String, pub init_system: String, } impl Default for SystemConfig { fn default() -> Self { Self { distro_name: "Phoebus OS".into(), distro_id: "phoebus".into(), arch: "x86_64".into(), hostname: "phoebus".into(), keymap: "us".into(), locale: "en_US.UTF-8".into(), timezone: "UTC".into(), root_shell: "/bin/bash".into(), init_system: "systemd".into(), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct UserConfig { pub username: String, pub fullname: String, #[serde(deserialize_with = "de_string_or_seq")] pub groups: Vec, pub home: String, } impl Default for UserConfig { fn default() -> Self { Self { username: String::new(), fullname: "Phoebus User".into(), groups: split_list("wheel,audio,video,input,render,plugdev,libinput,network,power"), home: "/home".into(), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct StorageConfig { pub disk: String, pub partition_scheme: String, pub efi_size_mib: u32, pub efi_mount: String, pub swap_size_mib: u32, pub filesystem: Filesystem, pub btrfs_label: String, pub compress: String, pub install_root: String, #[serde(deserialize_with = "de_string_or_seq")] pub subvols: Vec, } impl Default for StorageConfig { fn default() -> Self { Self { disk: String::new(), partition_scheme: "whole_disk".into(), efi_size_mib: 1024, efi_mount: "/efi".into(), swap_size_mib: 0, filesystem: Filesystem::Btrfs, btrfs_label: "phoebus".into(), compress: "zstd:3".into(), install_root: "/mnt/phoebus".into(), subvols: split_list("@ @home @var @snapshots @swap"), } } } impl StorageConfig { /// The subvolume mounted at `/` (the first listed subvolume). pub fn root_subvolume(&self) -> String { self.subvols .first() .cloned() .unwrap_or_else(|| "@".to_string()) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct EncryptionConfig { pub mode: Encryption, pub name: String, pub cipher: String, pub key_size: u32, pub pbkdf: String, } impl Default for EncryptionConfig { fn default() -> Self { Self { mode: Encryption::Luks2, name: "cryptroot".into(), cipher: "aes-xts-plain64".into(), key_size: 512, pbkdf: "argon2id".into(), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct Stage3Config { pub url: String, pub sha256: String, pub mirror: String, pub gentoo_profile: String, pub binhost_uri: String, } impl Default for Stage3Config { fn default() -> Self { Self { url: String::new(), sha256: String::new(), mirror: "https://distfiles.gentoo.org/releases/amd64/autobuilds".into(), gentoo_profile: "default/linux/amd64/23.0/systemd".into(), binhost_uri: "https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64" .into(), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct KernelConfig { pub profile: KernelProfile, pub package: String, pub uki: bool, pub console: String, pub keep_kernels: u32, pub secureboot: bool, } impl Default for KernelConfig { fn default() -> Self { Self { profile: KernelProfile::Optimized, package: "sys-kernel/gentoo-kernel".into(), uki: false, console: "console=tty0".into(), keep_kernels: 3, secureboot: false, } } } impl KernelConfig { /// The kernel package the profile resolves to. pub fn selected_package(&self) -> String { match self.profile { KernelProfile::Safe => "sys-kernel/gentoo-kernel-bin".to_string(), KernelProfile::Optimized | KernelProfile::Aggressive => { if self.package.is_empty() { "sys-kernel/gentoo-kernel".to_string() } else { self.package.clone() } } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct PackagesConfig { pub policy: PackagePolicy, pub binary_packages: bool, pub accept_license: String, } impl Default for PackagesConfig { fn default() -> Self { Self { policy: PackagePolicy::Balanced, binary_packages: true, accept_license: "@FREE @BINARY-REDISTRIBUTABLE".into(), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct DesktopConfig { pub profile: DesktopProfile, pub flatpak: bool, pub audio_stack: String, } impl Default for DesktopConfig { fn default() -> Self { Self { profile: DesktopProfile::None, flatpak: false, audio_stack: "pipewire".into(), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(default)] pub struct AiConfig { pub enabled: bool, pub provider: String, pub model: String, pub endpoint: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct RuntimeConfig { pub dry_run: bool, pub assume_yes: bool, pub log_dir: String, pub state_dir: String, } impl Default for RuntimeConfig { fn default() -> Self { Self { dry_run: false, assume_yes: false, log_dir: "/var/log/phoebus-installer".into(), state_dir: "/run/phoebus-installer".into(), } } } // --------------------------------------------------------------------------- // Top level // --------------------------------------------------------------------------- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(default)] pub struct InstallConfig { pub system: SystemConfig, pub user: UserConfig, pub storage: StorageConfig, pub encryption: EncryptionConfig, pub stage3: Stage3Config, pub kernel: KernelConfig, pub packages: PackagesConfig, pub desktop: DesktopConfig, pub ai: AiConfig, pub runtime: RuntimeConfig, } impl InstallConfig { pub fn is_encrypted(&self) -> bool { self.encryption.mode != Encryption::None } pub fn target_disk(&self) -> &str { &self.storage.disk } /// Load a configuration from TOML or the legacy flat format. /// /// The legacy `KEY='value'` format is also *valid* TOML (single quotes are /// TOML literal strings), so format must be detected structurally rather /// than by attempting TOML first. pub fn load_from_path(path: &Path) -> Result { let text = std::fs::read_to_string(path) .map_err(|e| CoreError::io(path.to_path_buf(), e))?; if path.extension().and_then(|e| e.to_str()) == Some("toml") { return Self::from_toml(&text); } if looks_like_legacy(&text) { return Self::from_legacy(&text); } Self::from_toml(&text) } pub fn from_toml(text: &str) -> Result { let cfg: InstallConfig = toml::from_str(text)?; Ok(cfg) } pub fn to_toml_string(&self) -> Result { Ok(toml::to_string_pretty(self)?) } /// Parse the Bash prototype's flat `KEY='value'` configuration format. pub fn from_legacy(text: &str) -> Result { let mut cfg = InstallConfig::default(); for raw_line in text.lines() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { continue; }; let key = key.trim(); let value = unquote(value.trim()); cfg.apply_legacy_kv(key, &value)?; } Ok(cfg) } fn apply_legacy_kv(&mut self, key: &str, value: &str) -> Result<()> { match key { "DISTRO_NAME" => self.system.distro_name = value.into(), "DISTRO_ID" => self.system.distro_id = value.into(), "ARCH" => self.system.arch = value.into(), "HOSTNAME" => self.system.hostname = value.into(), "KEYMAP" => self.system.keymap = value.into(), "LOCALE" => self.system.locale = value.into(), "TIMEZONE" => self.system.timezone = value.into(), "ROOT_SHELL" => self.system.root_shell = value.into(), "INIT_SYSTEM" => self.system.init_system = value.into(), "USERNAME" => self.user.username = value.into(), "USER_FULLNAME" => self.user.fullname = value.into(), "USER_GROUPS" => self.user.groups = split_list(value), "USER_HOME" => self.user.home = value.into(), "TARGET_DISK" => self.storage.disk = value.into(), "PARTITION_SCHEME" => self.storage.partition_scheme = value.into(), "EFI_SIZE_MIB" => self.storage.efi_size_mib = parse_num(key, value)?, "EFI_MOUNT" => self.storage.efi_mount = value.into(), "SWAP_SIZE_MIB" => self.storage.swap_size_mib = parse_num(key, value)?, "FILESYSTEM" => self.storage.filesystem = Filesystem::from_str(value)?, "BTRFS_LABEL" => self.storage.btrfs_label = value.into(), "COMPRESS" => self.storage.compress = value.into(), "INSTALL_ROOT" => self.storage.install_root = value.into(), "BTRFS_SUBVOLS" => self.storage.subvols = split_list(value), "ENCRYPTION" => self.encryption.mode = Encryption::from_str(value)?, "LUKS_NAME" => self.encryption.name = value.into(), "LUKS_CIPHER" => self.encryption.cipher = value.into(), "LUKS_KEY_SIZE" => self.encryption.key_size = parse_num(key, value)?, "LUKS_PBKDF" => self.encryption.pbkdf = value.into(), "STAGE3_URL" => self.stage3.url = value.into(), "STAGE3_SHA256" => self.stage3.sha256 = value.into(), "STAGE3_MIRROR" => self.stage3.mirror = value.into(), "GENTOO_PROFILE" => self.stage3.gentoo_profile = value.into(), "BINHOST_URI" => self.stage3.binhost_uri = value.into(), "BOOTLOADER" => { // Bootloader is currently fixed to systemd-boot; validate value. let _ = Bootloader::from_str(value)?; } "KERNEL_PROFILE" => self.kernel.profile = KernelProfile::from_str(value)?, "KERNEL_PACKAGE" => self.kernel.package = value.into(), "KERNEL_UKI" => self.kernel.uki = parse_bool(value), "KERNEL_CONSOLE" => self.kernel.console = value.into(), "KEEP_KERNELS" => self.kernel.keep_kernels = parse_num(key, value)?, "SECUREBOOT" => self.kernel.secureboot = parse_bool(value), "PACKAGE_POLICY" => self.packages.policy = PackagePolicy::from_str(value)?, "FEATURES_BINPKG" => self.packages.binary_packages = parse_bool(value), "ACCEPT_LICENSE" => self.packages.accept_license = value.into(), "DESKTOP_PROFILE" => self.desktop.profile = DesktopProfile::from_str(value)?, "FLATPAK" => self.desktop.flatpak = parse_bool(value), "AUDIO_STACK" => self.desktop.audio_stack = value.into(), "AI_ENABLED" => self.ai.enabled = parse_bool(value), "AI_PROVIDER" => self.ai.provider = value.into(), "AI_MODEL" => self.ai.model = value.into(), "AI_ENDPOINT" => self.ai.endpoint = value.into(), "DRY_RUN" => self.runtime.dry_run = parse_bool(value), "ASSUME_YES" => self.runtime.assume_yes = parse_bool(value), "LOG_DIR" => self.runtime.log_dir = value.into(), // Ignored legacy keys (not part of the Rust model yet). _ => {} } Ok(()) } } /// True when the text looks like the Bash prototype's flat `KEY='value'` file. fn looks_like_legacy(text: &str) -> bool { for raw in text.lines() { let line = raw.trim(); if line.is_empty() || line.starts_with('#') || line.starts_with('[') { continue; } if line.contains('=') { let key = line.split('=').next().unwrap().trim(); if !key.is_empty() && key .chars() .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') { return true; } } } false } fn parse_bool(value: &str) -> bool { matches!( value.trim().to_ascii_lowercase().as_str(), "yes" | "true" | "1" | "on" | "y" ) } fn parse_num(field: &str, value: &str) -> Result { value.trim().parse::().map_err(|_| { CoreError::Config(format!("{field} must be a positive integer, got `{value}`")) }) } fn unquote(value: &str) -> String { let bytes = value.as_bytes(); if bytes.len() >= 2 && ((bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\'') || (bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')) { value[1..value.len() - 1].to_string() } else { value.to_string() } } /// The install root as a path. impl StorageConfig { pub fn install_root_path(&self) -> PathBuf { PathBuf::from(&self.install_root) } } #[cfg(test)] mod tests { use super::*; #[test] fn defaults_match_bash_baseline() { let c = InstallConfig::default(); assert_eq!(c.system.hostname, "phoebus"); assert_eq!(c.user.groups.len(), 9); assert_eq!(c.storage.filesystem, Filesystem::Btrfs); assert_eq!(c.encryption.mode, Encryption::Luks2); assert_eq!(c.encryption.name, "cryptroot"); assert_eq!(c.stage3.binhost_uri.contains("binpackages"), true); assert_eq!(c.kernel.console, "console=tty0"); assert!(c.packages.binary_packages); assert!(!c.packages.policy.eq(&PackagePolicy::SourceFirst)); } #[test] fn legacy_config_parses_flat_keys() { let text = "\ HOSTNAME='testbox'\n\ USERNAME='alice'\n\ USER_GROUPS=\"wheel,audio,video\"\n\ TARGET_DISK='/dev/vda'\n\ ENCRYPTION='luks2'\n\ FILESYSTEM='btrfs'\n\ KERNEL_PROFILE='safe'\n\ DESKTOP_PROFILE='none'\n\ STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz'\n\ STAGE3_SHA256='abc'\n"; let c = InstallConfig::from_legacy(text).unwrap(); assert_eq!(c.system.hostname, "testbox"); assert_eq!(c.user.username, "alice"); assert_eq!(c.user.groups, vec!["wheel", "audio", "video"]); assert_eq!(c.storage.disk, "/dev/vda"); assert_eq!(c.kernel.profile, KernelProfile::Safe); assert_eq!(c.kernel.selected_package(), "sys-kernel/gentoo-kernel-bin"); assert_eq!(c.stage3.url, "http://10.0.2.2:8000/stage3.tar.xz"); } #[test] fn toml_roundtrip() { let mut c = InstallConfig::default(); c.system.hostname = "box".into(); c.storage.subvols = vec!["@".into(), "@home".into()]; c.desktop.profile = DesktopProfile::Dwl; let text = c.to_toml_string().unwrap(); // The deserializer accepts a bare string for list fields too. let back = InstallConfig::from_toml(&text).unwrap(); assert_eq!(back.system.hostname, "box"); assert_eq!(back.storage.subvols, vec!["@", "@home"]); assert_eq!(back.desktop.profile, DesktopProfile::Dwl); } #[test] fn toml_accepts_string_lists() { let text = "\ [user]\ngroups = \"wheel,audio\"\n\ [storage]\nsubvols = \"@ @home @var\"\n"; let c = InstallConfig::from_toml(text).unwrap(); assert_eq!(c.user.groups, vec!["wheel", "audio"]); assert_eq!(c.storage.subvols, vec!["@", "@home", "@var"]); } #[test] fn load_from_path_detects_legacy_format() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("test.conf"); std::fs::write( &path, "HOSTNAME='box'\nTARGET_DISK='/dev/vda'\nKERNEL_PROFILE='safe'\n", ) .unwrap(); let c = InstallConfig::load_from_path(&path).unwrap(); assert_eq!(c.system.hostname, "box"); assert_eq!(c.storage.disk, "/dev/vda"); assert_eq!(c.kernel.profile, KernelProfile::Safe); } #[test] fn load_from_path_parses_toml() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("test.toml"); std::fs::write(&path, "[system]\nhostname = \"tomlbox\"\n").unwrap(); let c = InstallConfig::load_from_path(&path).unwrap(); assert_eq!(c.system.hostname, "tomlbox"); } #[test] fn unknown_enum_value_is_rejected() { let text = "[storage]\nfilesystem = \"zfs\"\n"; assert!(InstallConfig::from_toml(text).is_err()); } }