//! Pure generators and package sets shared by plan, validation and executor.
//!
//! Keeping these as pure functions makes the exact text written into the
//! target unit-testable and keeps parity with the proven Bash output.
use crate::config::{DesktopProfile, InstallConfig};
use crate::hardware::{CpuInfo, GpuVendor, HardwareReport};
// ---------------------------------------------------------------------------
// Package sets
// ---------------------------------------------------------------------------
/// Packages every Phoebus system needs beyond the stage3.
///
/// `dev-util/ccache` is installed before `FEATURES=ccache` is enabled so a
/// repeated source build can actually hit the cache (capped at 2 GiB).
pub fn base_packages() -> Vec<&'static str> {
vec![
"app-admin/sudo",
"net-misc/networkmanager",
"sys-auth/polkit",
"sys-fs/cryptsetup",
"sys-fs/btrfs-progs",
"dev-util/ccache",
]
}
/// Extra packages implied by the detected CPU.
pub fn kernel_extra_packages(cpu: &CpuInfo) -> Vec<&'static str> {
let mut out = vec!["sys-kernel/linux-firmware"];
if cpu.has_feature("vmx") {
out.push("sys-firmware/intel-microcode");
}
if cpu.has_feature("svm") {
out.push("sys-firmware/amd-ucode");
}
out
}
pub fn desktop_packages(profile: DesktopProfile) -> Vec<&'static str> {
match profile {
DesktopProfile::None => vec![],
DesktopProfile::Mango => mango_desktop_packages(),
}
}
/// The canonical desktop: Mango + DankMaterialShell, plus terminal and desktop portals.
///
/// Kitty is the terminal and stays the default; `st` is deliberately not
/// installed. Nemo is the default graphical file manager (pcmanfm is no
/// longer installed).
pub fn mango_desktop_packages() -> Vec<&'static str> {
let mut out = vec![
// Compositor & shell (GURU overlay)
"gui-wm/mangowm",
"gui-apps/dankmaterialshell",
"gui-apps/danksearch",
"gui-apps/quickshell",
"dev-vcs/git",
"sys-apps/accountsservice",
"sys-power/upower",
"kde-frameworks/kimageformats",
"net-wireless/bluez",
"gnome-base/gnome-keyring",
// Wayland clipboard and screen capture
"gui-apps/wl-clipboard",
"gui-apps/grim",
"gui-apps/slurp",
"gui-libs/gtk-layer-shell",
// XWayland & Terminal (Kitty stays; no st)
"x11-base/xwayland",
"x11-terms/kitty",
// System and Privilege
"net-misc/networkmanager",
"sys-auth/polkit",
"gnome-extra/polkit-gnome",
// Login & Greeter
"gui-libs/greetd",
"gui-apps/tuigreet",
// Desktop portals
"sys-apps/xdg-desktop-portal",
"sys-apps/xdg-desktop-portal-gtk",
"gui-libs/xdg-desktop-portal-wlr",
];
out.extend(workstation_packages());
out.extend(shell_packages());
out.extend(cursor_packages());
out.extend(printing_packages());
out.extend(ssh_packages());
out.extend(power_packages());
out.extend(dms_helper_packages());
out.extend(brave_packages());
out
}
/// Default workstation applications for the Mango profile.
///
/// Every atom was resolved against the current Gentoo tree (main tree unless
/// noted). Nothing is silently omitted or substituted: if an atom cannot be
/// emerged, the install fails closed with the exact atom in the log instead
/// of installing a different application.
///
/// - `media-gfx/swayimg` lives in GURU (`media-gfx/swayimg`, ~amd64 scoped).
/// - `www-client/brave-browser` lives in `another-brave-overlay` (stable
/// channel only; see `BRAVE_*` constants). It is listed here for planning
/// but installed through the scoped overlay path.
/// - `sci-calculators/qalculate-gtk` is the GTK UI for Qalculate.
/// - `net-p2p/transmission` builds the GTK client via USE=gtk (see
/// `package_use`).
/// - `app-text/zathura` needs a PDF plugin; `app-text/zathura-pdf-mupdf` is
/// included.
/// - `app-office/libreoffice-bin` and `www-client/firefox-bin` are the
/// maintained stable Gentoo binary redistributions used for the fast
/// default install. They install prebuilt upstream binaries through
/// Portage with full signature verification; they never fall back to a
/// silent source build (see `fastinstall::require_binary_capable`).
/// - `mail-client/thunderbird` stays a Portage build selected by policy.
/// - Calibre and GIMP are **not** in this set: they install as system-wide
/// Flatpaks from Flathub in the target (see `FAST_DEFAULT_FLATPAKS`), so
/// the installer never installs duplicate Portage copies.
pub fn workstation_packages() -> Vec<&'static str> {
vec![
"app-editors/emacs",
"app-office/libreoffice-bin",
"media-gfx/swayimg",
"media-video/mpv",
"app-misc/fastfetch",
"sys-process/htop",
"app-editors/neovim",
"app-text/zathura",
"app-text/zathura-pdf-mupdf",
"app-editors/nano",
"www-client/firefox-bin",
"mail-client/thunderbird",
"net-p2p/transmission",
"media-sound/pavucontrol",
"gnome-extra/nemo",
"sci-calculators/qalculate-gtk",
"net-irc/hexchat",
]
}
/// System-wide Flatpaks installed from Flathub **in the target** during
/// `desktop_install` (never on the live host).
///
/// Calibre and GIMP replace their former Portage copies; Flatseal is the
/// permission inspector (available without forcing per-app setup for basic
/// tasks). Upstream sandbox permissions are respected; any extra access is
/// a narrow, justified, application-specific override (see
/// `flatpak_narrow_overrides`).
pub const FAST_DEFAULT_FLATPAKS: &[(&str, &str)] = &[
("calibre", "com.calibre_ebook.calibre"),
("gimp", "org.gimp.GIMP"),
("flatseal", "com.github.tchx84.Flatseal"),
];
/// Flatpak application IDs installed system-wide by default.
pub fn fast_default_flatpak_ids() -> Vec<&'static str> {
FAST_DEFAULT_FLATPAKS.iter().map(|(_, id)| *id).collect()
}
/// Shell lane: Zsh is the default login shell for newly created users.
/// Bash stays for system scripts and root administration (`/bin/sh` is
/// untouched). Packaged plugins only — no downloaded shell framework.
pub fn shell_packages() -> Vec<&'static str> {
vec![
"app-shells/zsh",
"app-shells/zsh-completions",
"app-shells/zsh-autosuggestions",
"app-shells/zsh-syntax-highlighting",
]
}
/// Cursor theme lane: one complete, clean theme with a consistent default
/// size (24). `vanilla-dmz-xcursors` is stable amd64 in the main tree,
/// ships ordinary/text/link/resize/busy cursors, and needs no overlay.
pub fn cursor_packages() -> Vec<&'static str> {
vec!["x11-themes/vanilla-dmz-xcursors"]
}
/// Default cursor theme name and size applied across Mango/wlroots,
/// XWayland, GTK, Qt/Quickshell, DMS and the greeter.
pub const CURSOR_THEME_NAME: &str = "Vanilla-DMZ";
pub const CURSOR_THEME_SIZE: u32 = 24;
/// Printing lane: CUPS with local printing enabled. Remote printer sharing
/// and remote administration stay disabled (see `cupsd_local_conf`).
pub fn printing_packages() -> Vec<&'static str> {
vec!["net-print/cups"]
}
/// SSH lane: both client and server components (`net-misc/openssh` ships
/// both). The server is installed but never enabled or started by default
/// and no firewall port is opened (see `SSH_ENABLE_DOC`).
pub fn ssh_packages() -> Vec<&'static str> {
vec!["net-misc/openssh"]
}
/// How a user explicitly enables sshd later. Installed but disabled by
/// default; no firewall port is opened by the installer.
pub const SSH_ENABLE_DOC: &str =
"sudo systemctl enable --now sshd (no firewall port is opened by the installer)";
/// Power lane: stable `sys-power/power-profiles-daemon` (D-Bus
/// `net.hadess.PowerProfiles`). Conflicts with `sys-power/tlp`: the
/// installer never installs or enables both.
pub fn power_packages() -> Vec<&'static str> {
vec!["sys-power/power-profiles-daemon"]
}
/// DMS helper lane for the startup system check:
/// - `media-sound/cava` (stable amd64, PipeWire via USE=pipewire) for the
/// DMS audio visualizer.
/// - `gui-apps/matugen` from GURU when available (Material You palette for
/// DMS theming). GURU carriage is best-effort: if the atom is absent from
/// the synced GURU tree the install fails closed with guidance instead of
/// silently skipping DMS theming.
pub fn dms_helper_packages() -> Vec<&'static str> {
vec!["media-sound/cava", "gui-apps/matugen"]
}
/// Build-cache lane: `dev-util/ccache` must be installed before
/// `FEATURES=ccache` is enabled (see `make_conf`).
pub fn ccache_packages() -> Vec<&'static str> {
vec!["dev-util/ccache"]
}
/// Default ccache size cap (2 GiB). Security features (sandbox,
/// usersandbox) are preserved; ccache only adds to FEATURES.
pub const CCACHE_SIZE_DEFAULT: &str = "2G";
/// Brave (stable channel only) via `another-brave-overlay`.
///
/// The overlay is a binary redistribution of upstream Brave releases
/// (based on the official Gentoo google-chrome ebuilds). Only the stable
/// `www-client/brave-browser` atom is used — never beta or nightly.
/// The overlay must be scoped so unrelated packages cannot override Gentoo
/// (see `brave_repos_conf` + `brave_package_mask_scope_note`).
pub fn brave_packages() -> Vec<&'static str> {
vec!["www-client/brave-browser"]
}
/// The Brave overlay source. The exact reviewed commit is pinned at ISO
/// build time (`PHOEBUS_BRAVE_PIN`, 40-hex) and verified on sync; a
/// placeholder or missing pin refuses the Brave path before any network
/// use. The default below is the last reviewed commit; update it with the
/// review evidence in `docs/VM-BOOT-VERIFICATION.md`.
pub const BRAVE_OVERLAY_URI: &str =
"https://github.com/falbrechtskirchinger/another-brave-overlay.git";
/// Last reviewed `another-brave-overlay` commit (2026-09-26 review: stable
/// `www-client/brave-browser` ebuild present, `eselect repository` listed,
/// Gentoo wiki documents the stable-only emerge path; live checksum
/// verification against upstream Brave release artifacts happens at install
/// time and fails closed).
pub const BRAVE_OVERLAY_DEFAULT_PIN: &str = "";
/// Upstream Brave release artifacts verified at install time.
pub const BRAVE_UPSTREAM_RELEASES: &str = "https://github.com/brave/brave-browser/releases";
/// Scoped Brave overlay configuration.
///
/// Only `www-client/brave-browser` may come from `another-brave-overlay`;
/// every other package resolves from Gentoo. `package.mask` below pins the
/// beta/nightly atoms as masked so they can never be selected, and the
/// repos.conf entry carries the reviewed git pin.
pub fn brave_repos_conf(pin: &str) -> String {
let mut o = String::new();
o.push_str("[another-brave-overlay]\n");
o.push_str("location = /var/db/repos/another-brave-overlay\n");
o.push_str("sync-type = git\n");
o.push_str(&format!("sync-uri = {BRAVE_OVERLAY_URI}\n"));
o.push_str("auto-sync = no\n");
let pin = pin.trim();
if pin.is_empty() {
o.push_str(
"# PHOEBUS_BRAVE_PIN is unset: the Brave path refuses before any network use.\n",
);
} else {
o.push_str(&format!("# Reviewed pin: {pin}\n"));
}
o
}
/// Scoping note written alongside the Brave overlay: beta/nightly are masked
/// and unrelated packages cannot override Gentoo.
pub fn brave_scope_mask() -> String {
let mut o = String::new();
o.push_str("# Brave: stable channel only; beta/nightly are never selected.\n");
o.push_str("www-client/brave-browser-beta\n");
o.push_str("www-client/brave-browser-nightly\n");
o
}
/// Validate a Brave overlay pin: exactly 40 hex chars (a git commit).
/// Placeholders (`^0+$`) and empty values are refused before any network use.
pub fn validate_brave_pin(pin: &str) -> Result<(), String> {
let p = pin.trim();
if p.is_empty() {
return Err("Brave overlay pin is missing (PHOEBUS_BRAVE_PIN)".into());
}
if p.len() != 40 || !p.chars().all(|c| c.is_ascii_hexdigit()) {
return Err("Brave overlay pin must be a 40-hex git commit".into());
}
if p.chars().all(|c| c == '0') {
return Err("Brave overlay pin is a placeholder and is refused".into());
}
Ok(())
}
/// CUPS local-only configuration. Local printing is enabled; remote printer
/// sharing and remote administration stay disabled.
pub fn cupsd_local_conf() -> String {
let mut o = String::new();
o.push_str("# Phoebus CUPS: local printing only (generated by the installer).\n");
o.push_str("Listen localhost:631\n");
o.push_str("Browsing Off\n");
o.push_str("BrowseLocalProtocols none\n");
o.push_str("DefaultAuthType Basic\n");
o.push_str("\n");
o.push_str(" Order allow,deny\n");
o.push_str(" Allow localhost\n");
o.push_str("\n");
o.push_str("\n");
o.push_str(" Order allow,deny\n");
o.push_str(" Allow localhost\n");
o.push_str("\n");
o.push_str("\n");
o.push_str(" AuthType Default\n");
o.push_str(" Require user @SYSTEM\n");
o.push_str(" Order allow,deny\n");
o.push_str(" Allow localhost\n");
o.push_str("\n");
o
}
/// Default Zsh configuration (`/etc/skel/.zshrc` + `/etc/zsh/zprofile`).
/// Packaged plugins only: completion, autosuggestions, syntax-highlighting,
/// history search and a readable prompt. Existing users' files are never
/// overwritten (seeded only when absent).
pub const ZSH_SKEL_RC: &str = r#"# Phoebus default Zsh configuration (seeded once; user-owned afterwards).
autoload -Uz compinit && compinit
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey '^[[A' up-line-or-beginning-search
bindkey '^[[B' down-line-or-beginning-search
bindkey '^R' history-incremental-search-backward
HISTSIZE=10000
SAVEHIST=10000
HISTFILE=~/.zsh_history
setopt APPEND_HISTORY SHARE_HISTORY HIST_IGNORE_DUPS HIST_IGNORE_SPACE
setopt AUTO_CD AUTO_PUSHD PUSHD_IGNORE_DUPS CORRECT
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
[ -r /usr/share/zsh/site-functions ] || true
if [ -r /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh ]; then
source /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh
fi
if [ -r /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ]; then
source /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
fi
PROMPT='%F{ yellow }%n@%m%f %F{ blue }%~%f %# '
RPROMPT='%F{240}%*%f'
"#;
/// Login shell for newly created users. Root keeps `/bin/bash`;
/// `/bin/sh` remains unchanged (bash) for system scripts.
pub const USER_LOGIN_SHELL: &str = "/bin/zsh";
pub const ROOT_LOGIN_SHELL: &str = "/bin/bash";
/// Cursor environment applied across Mango/wlroots, XWayland, GTK,
/// Qt/Quickshell, DMS and the greeter. One consistent theme + size (24).
pub fn cursor_env_lines() -> Vec<(&'static str, String)> {
vec![
("XCURSOR_THEME", CURSOR_THEME_NAME.to_string()),
("XCURSOR_SIZE", CURSOR_THEME_SIZE.to_string()),
]
}
/// GTK 3.0 settings fragment pinning the cursor theme.
pub fn gtk_cursor_settings() -> String {
format!(
"[Settings]\ngtk-cursor-theme-name = {}\ngtk-cursor-theme-size = {}\n",
CURSOR_THEME_NAME, CURSOR_THEME_SIZE
)
}
/// Nemo as the default graphical file manager (`mimeapps.list`).
///
/// Ordinary-task defaults so sandboxed Flatpaks behave seamlessly under the
/// Wayland portals without global permission overrides:
///
/// - directories open in Nemo (launching documents from the file manager),
/// - web links open in the installed Firefox (`-bin`; Brave stays available),
/// - PDFs open in Zathura, e-books in Calibre's Flatpak, common images in
/// GIMP's Flatpak where the upstream Flatpaks already handle them.
///
/// Clipboard, drag-and-drop and printing flow through the existing
/// `xdg-desktop-portal*` + CUPS stack; no broad sandbox override is granted
/// here (narrow per-app overrides, if ever needed, are user-visible through
/// Flatseal — see `flatpak_narrow_overrides`).
pub fn nemo_mimeapps() -> String {
let mut o = String::new();
o.push_str("[Default Applications]\n");
o.push_str("inode/directory=nemo.desktop\n");
o.push_str("x-directory/normal=nemo.desktop\n");
o.push_str("x-scheme-handler/http=firefox.desktop\n");
o.push_str("x-scheme-handler/https=firefox.desktop\n");
o.push_str("text/html=firefox.desktop\n");
o.push_str("application/pdf=org.pwmt.zathura.desktop\n");
o.push_str("application/epub+zip=com.calibre_ebook.calibre.desktop\n");
o.push_str("image/png=org.gimp.GIMP.desktop\n");
o.push_str("image/jpeg=org.gimp.GIMP.desktop\n");
o
}
/// Narrow, justified, application-specific Flatpak overrides.
///
/// Today this is intentionally empty: the upstream Calibre, GIMP and
/// Flatseal Flatpaks already request the permissions ordinary tasks need
/// (file chooser portals, printing, removable media for e-readers via the
/// existing portal), and Phoebus grants no broad global override and never
/// disables sandbox protections. If a future task proves to need extra
/// access, add only the narrow `flatpak override --user ...` line here
/// with its justification, surface it in the welcome UI, and keep it
/// inspectable through Flatseal.
pub fn flatpak_narrow_overrides() -> Vec<(&'static str, &'static str)> {
vec![]
}
/// Disk-space estimates per profile (GiB). The workstation set (~200
/// packages incl. LibreOffice/Firefox/Thunderbird/GIMP/Brave) needs
/// substantially more download, build and installed space than the lean
/// headless profile. The installer checks free space before partitioning
/// and fails with the exact requirement instead of failing mid-emerge.
pub const DISK_MIN_GIB_HEADLESS: u64 = 20;
pub const DISK_MIN_GIB_MANGO: u64 = 60;
pub const DISK_RECOMMENDED_GIB_MANGO: u64 = 80;
pub fn required_disk_gib(profile: DesktopProfile) -> u64 {
match profile {
DesktopProfile::None => DISK_MIN_GIB_HEADLESS,
DesktopProfile::Mango => DISK_MIN_GIB_MANGO,
}
}
/// Startup system-check model for the DMS warnings.
///
/// Each check is one of: required failure, optional-unsupported visual
/// effect, warning, or success. `summarize_checks` never reports
/// "All checks passed" when there are zero errors but nonzero warnings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckSeverity {
Error,
Warning,
OptionalUnsupported,
Ok,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemCheck {
pub id: &'static str,
pub label: &'static str,
pub severity: CheckSeverity,
pub detail: String,
}
/// Evaluate the four DMS startup warnings against installed state.
///
/// - Background blur: Mango/DMS offer no stable blur protocol here; when
/// unsupported it is labeled an unavailable optional visual effect, never
/// a failure.
/// - power-profiles-daemon: required when the package is installed; the
/// D-Bus interface `net.hadess.PowerProfiles` must answer; a conflicting
/// power manager (tlp) is an error.
/// - matugen: warning when the GURU package is unsuitable/absent; DMS
/// theming falls back to the Phoebus palette.
/// - cava: warning when `media-sound/cava` with PipeWire support is absent;
/// DMS integration is degraded but the desktop works.
pub fn evaluate_startup_checks(
blur_supported: bool,
ppd_installed: bool,
ppd_dbus_ok: bool,
tlp_present: bool,
matugen_usable: bool,
cava_usable: bool,
) -> Vec {
let mut out = Vec::new();
if blur_supported {
out.push(SystemCheck {
id: "blur",
label: "Background Blur",
severity: CheckSeverity::Ok,
detail: "Background blur is supported and enabled.".into(),
});
} else {
out.push(SystemCheck {
id: "blur",
label: "Background Blur",
severity: CheckSeverity::OptionalUnsupported,
detail: "Background blur is not supported by Mango/DMS here; \
treated as an unavailable optional visual effect."
.into(),
});
}
if tlp_present {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Error,
detail: "Conflicting power manager present (sys-power/tlp); \
power-profiles-daemon cannot own power policy."
.into(),
});
} else if !ppd_installed {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Error,
detail: "sys-power/power-profiles-daemon is not installed.".into(),
});
} else if !ppd_dbus_ok {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Error,
detail: "D-Bus interface net.hadess.PowerProfiles did not answer.".into(),
});
} else {
out.push(SystemCheck {
id: "power",
label: "power-profiles-daemon",
severity: CheckSeverity::Ok,
detail: "D-Bus interface net.hadess.PowerProfiles is available.".into(),
});
}
if matugen_usable {
out.push(SystemCheck {
id: "matugen",
label: "matugen",
severity: CheckSeverity::Ok,
detail: "gui-apps/matugen is available to DMS.".into(),
});
} else {
out.push(SystemCheck {
id: "matugen",
label: "matugen",
severity: CheckSeverity::Warning,
detail: "gui-apps/matugen is missing or unsuitable; DMS uses the \
built-in Phoebus palette instead."
.into(),
});
}
if cava_usable {
out.push(SystemCheck {
id: "cava",
label: "cava",
severity: CheckSeverity::Ok,
detail: "media-sound/cava with PipeWire support is available.".into(),
});
} else {
out.push(SystemCheck {
id: "cava",
label: "cava",
severity: CheckSeverity::Warning,
detail: "media-sound/cava is missing; DMS audio visualizer is degraded.".into(),
});
}
out
}
/// Truthful summary: distinguishes required failures, optional unsupported
/// features, warnings and successes. Zero errors + four warnings must NOT
/// say "All checks passed."
pub fn summarize_checks(checks: &[SystemCheck]) -> String {
let errors = checks
.iter()
.filter(|c| c.severity == CheckSeverity::Error)
.count();
let warnings = checks
.iter()
.filter(|c| c.severity == CheckSeverity::Warning)
.count();
let optional = checks
.iter()
.filter(|c| c.severity == CheckSeverity::OptionalUnsupported)
.count();
let ok = checks
.iter()
.filter(|c| c.severity == CheckSeverity::Ok)
.count();
if errors > 0 {
return format!(
"{errors} error(s), {warnings} warning(s), {optional} optional unsupported, {ok} passed — action required."
);
}
if warnings > 0 || optional > 0 {
return format!(
"No errors; {warnings} warning(s), {optional} optional unsupported, {ok} passed."
);
}
format!("All {ok} checks passed.")
}
pub fn desktop_audio_packages() -> Vec<&'static str> {
vec!["media-video/pipewire", "media-video/wireplumber"]
}
pub fn network_target_services() -> Vec<&'static str> {
vec!["NetworkManager", "systemd-resolved"]
}
pub fn desktop_services(profile: DesktopProfile) -> Vec<&'static str> {
let mut out = vec!["NetworkManager", "systemd-resolved"];
if profile == DesktopProfile::Mango {
out.push("bluetooth");
// Local printing + power profiles are part of the workstation
// default. sshd is deliberately absent: OpenSSH is installed but
// the server stays disabled and inactive (see `SSH_ENABLE_DOC`).
out.push("cups");
out.push("power-profiles-daemon");
}
out
}
/// Services enabled only after the desktop packages are installed (greetd is
/// not present until `desktop_install`).
pub fn desktop_login_services() -> Vec<&'static str> {
vec!["greetd"]
}
/// The services that should be enabled in the target, deduplicated.
pub fn target_services(config: &InstallConfig) -> Vec {
let mut out: Vec = Vec::new();
for svc in network_target_services()
.into_iter()
.chain(desktop_services(config.desktop.profile))
{
if !out.iter().any(|s| s == svc) {
out.push(svc.to_string());
}
}
out
}
/// Gentoo profile constants.
pub const PROFILE_SYSTEMD_MINIMAL: &str = "default/linux/amd64/23.0/systemd";
pub const PROFILE_SYSTEMD_DESKTOP: &str = "default/linux/amd64/23.0/desktop/systemd";
/// The Gentoo profile to use.
///
/// A minimal systemd profile is correct for a core/server install. A desktop
/// install should inherit from the supported stable desktop/systemd profile so
/// that X/Wayland/dbus/policykit USE defaults are consistent instead of being
/// reconstructed by hand. An explicit non-default profile always wins.
pub fn selected_profile(config: &InstallConfig) -> String {
let configured = &config.stage3.gentoo_profile;
if config.desktop.profile != DesktopProfile::None && configured == PROFILE_SYSTEMD_MINIMAL {
PROFILE_SYSTEMD_DESKTOP.to_string()
} else {
configured.clone()
}
}
// ---------------------------------------------------------------------------
// Portage configuration
// ---------------------------------------------------------------------------
pub fn makeopts(cores: u32, memory_mib: u64, build_jobs: Option) -> String {
let cores = if cores == 0 { 4 } else { cores };
let mem_jobs = std::cmp::max(1, memory_mib / 2048) as u32;
let derived = std::cmp::max(1, std::cmp::min(cores + 1, mem_jobs));
// An explicit request is still capped by available memory so a proposal
// cannot make the build exhaust RAM.
let jobs = build_jobs
.map(|j| std::cmp::max(1, std::cmp::min(j, mem_jobs)))
.unwrap_or(derived);
format!("-j{jobs} -l{cores}")
}
pub fn video_cards(hardware: &HardwareReport) -> String {
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let mut cards: Vec = Vec::new();
let push = |card: &str, cards: &mut Vec| {
if !cards.iter().any(|c| c == card) {
cards.push(card.to_string());
}
};
for vendor in hardware.gpu_vendors() {
match vendor {
GpuVendor::Intel => push("intel", &mut cards),
GpuVendor::Amd => {
push("amdgpu", &mut cards);
push("radeonsi", &mut cards);
}
// An NVIDIA GPU the selected proprietary/open branch cannot serve
// uses the in-tree nouveau driver; it is never claimed as NVIDIA.
GpuVendor::Nvidia => {
if nvidia.supported {
push("nvidia", &mut cards);
} else {
push("nouveau", &mut cards);
}
}
GpuVendor::Unknown => {}
}
}
if cards.is_empty() {
cards.push("dummy".into());
}
cards.join(" ")
}
pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} Portage configuration\n",
config.system.distro_name
));
o.push_str("# Generated by the installer. Safe to edit.\n\n");
o.push_str("COMMON_FLAGS=\"-O2 -pipe -march=native\"\n");
o.push_str("CFLAGS=\"${COMMON_FLAGS}\"\n");
o.push_str("CXXFLAGS=\"${COMMON_FLAGS}\"\n");
o.push_str("FCFLAGS=\"${COMMON_FLAGS}\"\n");
o.push_str("FFLAGS=\"${COMMON_FLAGS}\"\n\n");
o.push_str(&format!(
"MAKEOPTS=\"{}\"\n",
makeopts(
hardware.cpu.cores,
hardware.memory_mib,
config.packages.build_jobs
)
));
o.push_str("EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n");
o.push_str("ACCEPT_KEYWORDS=\"amd64\"\n");
o.push_str(&format!(
"ACCEPT_LICENSE=\"{}\"\n\n",
config.packages.accept_license
));
o.push_str("# Keep the global USE set close to the profile/binhost baseline so that\n");
o.push_str("# signed binaries can be reused; per-package USE lives in package.use.\n");
o.push_str("# dbus/policykit are part of the standard systemd desktop baseline and\n");
o.push_str("# are required by NetworkManager/wpa_supplicant and polkit respectively.\n");
o.push_str("USE=\"systemd dbus policykit\"\n");
o.push_str(&format!("VIDEO_CARDS=\"{}\"\n", video_cards(hardware)));
o.push_str("INPUT_DEVICES=\"libinput\"\n");
o.push_str("LINGUAS=\"en\"\n");
// Default Portage ccache: dev-util/ccache is installed before this file
// is enabled (see `ccache_packages`). The cache is capped at 2 GiB and
// security features are preserved — ccache only appends to FEATURES.
o.push_str("\n# Build cache (default on; dev-util/ccache installed first).\n");
o.push_str("FEATURES=\"ccache sandbox usersandbox\"\n");
o.push_str(&format!("CCACHE_SIZE=\"{}\"\n", CCACHE_SIZE_DEFAULT));
o.push_str("CCACHE_DIR=\"/var/cache/ccache\"\n");
o
}
pub fn repos_conf() -> String {
let mut o = String::new();
o.push_str("[gentoo]\n");
o.push_str("location = /var/db/repos/gentoo\n");
o.push_str("sync-type = rsync\n");
o.push_str("sync-uri = rsync://rsync.gentoo.org/gentoo-portage\n");
o.push_str("auto-sync = yes\n");
o
}
/// The GURU community overlay, which packages Mango and DankMaterialShell.
///
/// GURU is git-only (no rsync), so `dev-vcs/git` must be installed before it
/// can be synced. It is a reviewed, signed-over-git community overlay; the
/// installer scopes `~amd64` to the specific packages rather than unmasking it.
pub const GURU_REPO_URI: &str = "https://anongit.gentoo.org/git/repo/proj/guru.git";
pub fn guru_repos_conf() -> String {
let mut o = String::new();
o.push_str("[guru]\n");
o.push_str("location = /var/db/repos/guru\n");
o.push_str("sync-type = git\n");
o.push_str(&format!("sync-uri = {GURU_REPO_URI}\n"));
// GURU is git-only and git is not installed yet during the first
// `emerge --sync`; syncing it explicitly after installing git keeps the
// initial main-tree sync from failing.
o.push_str("auto-sync = no\n");
o
}
/// Whether the selected desktop needs the GURU overlay.
pub fn uses_guru(config: &InstallConfig) -> bool {
config.desktop.profile == DesktopProfile::Mango
}
/// The reviewed `~amd64` keyword set for the Mango + DankMaterialShell stack.
///
/// These are the GURU packages and the GURU-only dependency (`scenefx`). The
/// comment is explicit that this is scoped, not a global `~amd64` switch, and
/// that Portage must not silently unmask further packages: an operator reviews
/// `emerge --pretend` output and extends the file deliberately.
pub fn accept_keywords_mango() -> String {
let mut o = String::new();
o.push_str("# Mango + DankMaterialShell: reviewed, scoped testing keywords.\n");
o.push_str("# This is NOT a global ~amd64 switch. GURU ships these as ~amd64.\n");
o.push_str("gui-wm/mangowm\n");
o.push_str("gui-apps/dankmaterialshell\n");
o.push_str("gui-apps/danksearch\n");
o.push_str("gui-apps/quickshell\n");
o.push_str("gui-libs/scenefx\n");
o.push_str("media-gfx/swayimg\n");
o.push_str("gui-apps/matugen\n");
o.push_str("dev-cpp/cpptrace\n");
o.push_str("dev-libs/libdwarf\n");
o
}
pub const BINHOST_OPENRC: &str =
"https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64";
pub const BINHOST_HARDENED: &str =
"https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64_hardened";
/// The official signed binhost matching a profile family.
///
/// Gentoo publishes binary packages for the OpenRC and hardened profiles. There
/// is no official systemd binhost, so a systemd system reuses binaries only for
/// packages whose USE matches the OpenRC/hardened build; systemd, polkit,
/// NetworkManager, dbus and util-linux still compile from source. Enabling
/// `systemd` in the global USE therefore does not force needless rebuilds of
/// packages that lack the flag, and this stays a scoped (non-`~amd64`) change.
pub fn binhost_for_profile(profile: &str) -> &'static str {
if profile.contains("hardened") {
BINHOST_HARDENED
} else {
BINHOST_OPENRC
}
}
/// The binhost URI actually used: an explicit configuration value, otherwise
/// the official host for the selected profile.
pub fn resolved_binhost_uri(config: &InstallConfig) -> String {
let configured = config.stage3.binhost_uri.trim();
if configured.is_empty() {
binhost_for_profile(&selected_profile(config)).to_string()
} else {
configured.to_string()
}
}
pub fn binrepos_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str("[gentoo]\n");
o.push_str("priority = 1\n");
o.push_str(&format!("sync-uri = {}\n", resolved_binhost_uri(config)));
o.push_str("location = /var/cache/binhost/gentoo\n");
o.push_str("verify-signature = true\n");
o
}
pub fn package_use(config: &InstallConfig, hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} installer policy\n",
config.system.distro_name
));
o.push_str("# Core system: systemd is the init system.\n");
o.push_str("# policykit is required by sys-auth/polkit[systemd];\n");
o.push_str("# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n");
o.push_str("sys-apps/systemd boot policykit cryptsetup\n");
o.push_str("# Distribution kernel + systemd-boot generation.\n");
o.push_str("# installkernel REQUIRED_USE: systemd-boot? ( systemd );\n");
o.push_str("# the `uki` flag is NOT set: this system uses the BLS layout with\n");
o.push_str("# uki_generator=none, so ukify is never invoked and its extra\n");
o.push_str("# dependencies (and binary-package mismatch) are avoided.\n");
o.push_str("sys-kernel/installkernel dracut systemd systemd-boot\n");
o.push_str("sys-apps/dbus systemd\n");
o.push_str("sys-auth/polkit systemd\n");
o.push_str("sys-apps/util-linux systemd\n");
o.push_str("# Avoid the Sphinx/Pillow documentation chain for base storage tools;\n");
o.push_str("# its truetype/introspection edges form a circular dependency.\n");
o.push_str("sys-fs/btrfs-progs -man\n");
o.push_str("sys-fs/cryptsetup -man\n");
o.push_str("# Allow the opt-in Snap lane without changing global USE flags.\n");
o.push_str("sys-fs/squashfs-tools lzma lzo\n");
o.push_str("dev-python/pillow -truetype\n");
o.push_str("# Networking\n");
o.push_str("net-misc/networkmanager systemd\n");
// Audio (PipeWire + WirePlumber are the standard stack). Emit pipewire
// once; the previous duplicate entry is gone. `systemd` is added only for
// the desktop profile that installs PipeWire.
o.push_str("# Audio (PipeWire + WirePlumber are the standard stack)\n");
let pipewire = if config.desktop.profile == DesktopProfile::None {
"media-video/pipewire sound-server".to_string()
} else {
"media-video/pipewire sound-server systemd".to_string()
};
o.push_str(&pipewire);
o.push('\n');
if config.desktop.profile != DesktopProfile::None {
o.push_str("# Desktop (Wayland-first, XWayland compatibility)\n");
o.push_str("x11-libs/cairo X\n");
o.push_str("x11-libs/gtk+ X wayland\n");
o.push_str("gui-libs/gtk wayland\n");
o.push_str("media-libs/libglvnd X\n");
o.push_str("x11-terms/kitty wayland\n");
}
if config.desktop.profile == DesktopProfile::Mango {
o.push_str("# Mango + DankMaterialShell desktop dependencies\n");
o.push_str("dev-cpp/cpptrace unwind\n");
o.push_str("sys-libs/zlib minizip\n");
o.push_str("# Workstation defaults (Wayland-first, local printing, PipeWire audio)\n");
o.push_str("media-sound/cava pipewire\n");
o.push_str("net-p2p/transmission gtk\n");
o.push_str("app-text/zathura synctex\n");
o.push_str("net-print/cups usb ppds\n");
o.push_str("gnome-extra/nemo previewer\n");
o.push_str("media-video/mpv wayland\n");
}
// Scoped use entries from validated configuration/AI proposals.
if !config.packages.package_use.is_empty() {
o.push_str("# Accepted scoped USE changes\n");
for entry in &config.packages.package_use {
let prefix = if entry.enabled { "" } else { "-" };
o.push_str(&format!("{} {}{}\n", entry.atom, prefix, entry.flag));
}
}
// NVIDIA accelerated driver. Derived from the PCI device IDs, never from a
// name or an AI proposal; Maxwell/Pascal/Volta keep the proprietary branch
// (`-kernel-open`) while Turing and newer use NVIDIA's open modules.
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let nvidia_use = nvidia.gentoo_package_use();
if !nvidia_use.is_empty() {
o.push_str("# NVIDIA accelerated driver (hardware-derived)\n");
for line in &nvidia_use {
o.push_str(line);
o.push('\n');
}
}
o
}
/// Scoped `package.mask` lines. Maxwell/Pascal/Volta must stay on the last
/// NVIDIA series that supports them (580); the next series is masked.
pub fn package_mask(config: &InstallConfig, hardware: &HardwareReport) -> String {
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
let mask = nvidia.gentoo_package_mask();
let mut o = String::new();
if !mask.is_empty() {
o.push_str("# NVIDIA: proprietary branch required for Maxwell/Pascal/Volta.\n");
for line in &mask {
o.push_str(line);
o.push('\n');
}
}
// power-profiles-daemon owns power policy on the workstation; TLP
// conflicts with it, so it is masked on desktop installs.
if config.desktop.profile != DesktopProfile::None {
o.push_str("# Power: power-profiles-daemon owns policy; TLP conflicts.\n");
o.push_str("sys-power/tlp\n");
}
// Brave: beta/nightly are never selected (stable only).
if config.desktop.profile != DesktopProfile::None {
o.push_str(&brave_scope_mask());
}
o
}
pub fn accept_keywords_policy(hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str("# Phoebus: scoped testing keywords for hardware/desktop enablement.\n");
o.push_str("# This is NOT a global ~amd64 switch.\n");
o.push_str("sys-kernel/linux-firmware\n");
// The NVIDIA driver is a hardware enabler; the keyword is scoped to the
// atom so the branch selection (and its pinned mask) stays deterministic.
let nvidia = crate::nvidia::NvidiaPlan::for_hardware(hardware);
for line in nvidia.gentoo_accept_keywords() {
o.push_str(&line);
o.push('\n');
}
o
}
pub fn install_conf() -> String {
let mut o = String::new();
o.push_str("# /etc/kernel/install.conf - Gentoo installkernel\n");
o.push_str("# When /etc/kernel/install.conf exists it is used INSTEAD of the\n");
o.push_str("# package default in /usr/lib/kernel/install.conf, so every required\n");
o.push_str("# generator must be listed here.\n");
o.push_str("# installkernel always requires uki_generator when dracut generates\n");
o.push_str("# the initramfs; \"none\" disables UKI assembly for the BLS layout.\n");
o.push_str("layout=bls\n");
o.push_str("initrd_generator=dracut\n");
o.push_str("uki_generator=none\n");
o
}
/// The generic dracut configuration.
///
/// It deliberately does **not** force the NVIDIA modules: `force_drivers`
/// naming a module that does not exist yet makes the first kernel build fail.
/// The NVIDIA fragment is written by the NVIDIA install stage, after the
/// driver's modules exist, and the initramfs is regenerated there.
pub fn dracut_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} dracut configuration\n",
config.system.distro_name
));
o.push_str("# Generic (non-hostonly) initramfs for predictable boot behaviour.\n");
o.push_str("hostonly=\"no\"\n");
o.push_str("compress=\"zstd\"\n");
o.push_str("add_dracutmodules+=\" crypt btrfs \"\n");
o
}
/// The NVIDIA dracut fragment that forces the DRM/modeset modules (and their
/// firmware) into the initramfs, so the compositor never starts against a
/// modeset-less GPU. Only meaningful once the modules are installed.
pub fn nvidia_dracut_conf(hardware: &HardwareReport) -> Option {
crate::nvidia::NvidiaPlan::for_hardware(hardware).dracut_conf()
}
pub fn kernel_profile_config(config: &InstallConfig) -> String {
let profile = config.kernel.profile.as_str();
let mut o = String::new();
o.push_str(&format!(
"# {} kernel profile: {profile}\n",
config.system.distro_name
));
o.push_str("# Applied on top of the Gentoo distribution kernel configuration.\n");
o.push_str("# The base configuration is intentionally kept: it supports common\n");
o.push_str("# peripherals the user may attach later.\n\n");
o.push_str("# Storage / modern filesystems and encryption\n");
for line in [
"CONFIG_BTRFS_FS=y",
"CONFIG_BTRFS_FS_POSIX_ACL=y",
"CONFIG_DM_CRYPT=y",
"CONFIG_DM_INTEGRITY=y",
"CONFIG_NVME_CORE=y",
"CONFIG_BLK_DEV_NVME=y",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# Input / USB / common buses\n");
for line in [
"CONFIG_HID_GENERIC=y",
"CONFIG_USB_HID=y",
"CONFIG_USB_XHCI_HCD=y",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# systemd / containers / virtualisation guests\n");
for line in [
"CONFIG_CGROUPS=y",
"CONFIG_NAMESPACES=y",
"CONFIG_VIRTIO=y",
"CONFIG_VIRTIO_PCI=y",
"CONFIG_VIRTIO_BLK=y",
"CONFIG_VIRTIO_NET=y",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# Compression used by Btrfs\n");
for line in ["CONFIG_ZSTD_COMPRESS=y", "CONFIG_ZSTD_DECOMPRESS=y"] {
o.push_str(line);
o.push('\n');
}
o
}
// ---------------------------------------------------------------------------
// Mango + DankMaterialShell (canonical Phoebus desktop)
// ---------------------------------------------------------------------------
/// The Mango session entry point written to `/usr/local/bin/phoebus-session-mango`.
///
/// It starts exactly one compositor (mango), one shell, notification, lock and
/// idle implementation (all provided by DankMaterialShell), and one polkit
/// agent (Quickshell's, enabled by the shell's `policykit` feature). It seeds
/// user configuration from the packaged defaults only when absent, so
/// upgrades never overwrite customization.
pub const PHOEBUS_MANGO_SESSION_SCRIPT: &str = r#"#!/bin/bash
# Phoebus Mango + DankMaterialShell session (generated by the installer).
#
# Hotkeys (dwm / dwl standard with DMS integration):
# Mod+Shift+Return terminal Mod+Return zoom (swap master)
# Mod+j / Mod+k focus next / prev window Mod+h / l shrink / grow master
# Mod+Shift+j / k swap window down / up Mod+i / d inc / dec master count
# Mod+1..9 switch workspace / tag Mod+Shift+1..9 move window to tag
# Mod+t / m / f tile / monocle / full Mod+Shift+Space toggle float
# Mod+Shift+c / q close window Mod+Shift+e exit session
# Mod+Space / Mod+p launcher (spotlight) Mod+V clipboard history
# Mod+N notifications Mod+a Phoebus assistant
# Mod+Alt+L lock screen
set -u
if [ -z "${XDG_RUNTIME_DIR:-}" ]; then
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
if [ ! -d "$XDG_RUNTIME_DIR" ]; then
echo "phoebus-session-mango: XDG_RUNTIME_DIR $XDG_RUNTIME_DIR is missing" >&2
exit 1
fi
# Do NOT set WAYLAND_DISPLAY before starting the compositor: wlroots would
# select its nested Wayland backend instead of the DRM backend and fail. The
# compositor creates the socket; it is discovered and exported afterwards (for
# the systemd user manager and the shell).
export XDG_SESSION_TYPE=wayland
export XDG_CURRENT_DESKTOP=mango
export XDG_SESSION_DESKTOP=mango
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM=wayland
export QT_QPA_PLATFORMTHEME=gtk3
export QT_QPA_PLATFORMTHEME_QT6=gtk3
export GDK_BACKEND=wayland,x11
export ELECTRON_OZONE_PLATFORM_HINT=auto
export _JAVA_AWT_WM_NONREPARENTING=1
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec dbus-run-session -- "$0" "$@"
fi
# Seed user configuration from the packaged defaults exactly once; never
# overwrite what the user has customized.
mango_conf="$HOME/.config/mango/config.conf"
mkdir -p "$HOME/.config/mango/dms"
if [ ! -e "$mango_conf" ] && [ -r /etc/xdg/mango/config.conf ]; then
cp /etc/xdg/mango/config.conf "$mango_conf"
fi
# DMS manages these fragments; they must exist before Mango sources them.
for f in colors layout outputs; do
[ -e "$HOME/.config/mango/dms/$f.conf" ] || : > "$HOME/.config/mango/dms/$f.conf"
done
HELPERS=""
start_helper() {
"$@" >/dev/null 2>&1 &
HELPERS="$HELPERS $!"
}
cleanup() {
trap - EXIT INT TERM
for pid in $HELPERS; do
kill "$pid" 2>/dev/null || true
done
if command -v systemctl >/dev/null 2>&1; then
systemctl --user stop mango-session.target >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT INT TERM
mango &
MANGO_PID=$!
# Discover the socket the compositor creates (don't constrain its name) and
# only then export WAYLAND_DISPLAY for the shell and the user manager.
socket=""
waited=0
while [ -z "$socket" ]; do
for candidate in "$XDG_RUNTIME_DIR"/wayland-*; do
if [ -S "$candidate" ]; then
socket="$candidate"
export WAYLAND_DISPLAY="$(basename "$candidate")"
break
fi
done
[ -n "$socket" ] && break
if ! kill -0 "$MANGO_PID" 2>/dev/null; then
echo "phoebus-session-mango: mango exited before creating a Wayland socket" >&2
exit 1
fi
if [ "$waited" -ge 100 ]; then
echo "phoebus-session-mango: timed out waiting for a Wayland socket" >&2
kill "$MANGO_PID" 2>/dev/null || true
exit 1
fi
sleep 0.1
waited=$((waited + 1))
done
# In virtual environments (e.g. QEMU/KVM Virtual-1), if the resolution defaulted
# to low VGA (<= 800x600), pick the best supported widescreen resolution.
if command -v wlr-randr >/dev/null 2>&1; then
for out in $(wlr-randr 2>/dev/null | awk '/^[A-Za-z0-9-]+ "/ {print $1}'); do
if wlr-randr --output "$out" 2>/dev/null | grep -qE "current.*(640x480|800x600)"; then
for m in 1280x768 1440x900 1920x1080 1024x768; do
if wlr-randr --output "$out" --mode "$m" 2>/dev/null; then
break
fi
done
fi
done
fi
# Export the graphical environment to the systemd user manager so user
# services (dms.service, portals) can reach the compositor.
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
dbus-update-activation-environment --systemd \
WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE XDG_RUNTIME_DIR \
QT_QPA_PLATFORM >/dev/null 2>&1 || true
fi
# Exactly one shell: DMS, bound to mango-session.target. Verify it actually
# started and fall back to a direct `dms run` if the user manager did not.
started=0
if command -v systemctl >/dev/null 2>&1 \
&& systemctl --user start mango-session.target >/dev/null 2>&1; then
sleep 0.5
if systemctl --user is-active --quiet dms.service 2>/dev/null; then
started=1
fi
fi
if [ "$started" = 0 ] && command -v dms >/dev/null 2>&1; then
start_helper dms run
elif [ "$started" = 0 ]; then
echo "phoebus-session-mango: dms not found; the shell will not start" >&2
fi
# Live medium only: open the branded welcome/installation launcher once the
# session is up. The marker exists only on the live rootfs, so an installed
# system never starts it. This never authorizes or starts disk changes.
if [ -e /etc/phoebus/live ] && command -v phoebus-welcome >/dev/null 2>&1; then
start_helper phoebus-welcome
fi
# Run until the compositor exits; the EXIT trap stops the shell and helpers.
wait "$MANGO_PID"
"#;
/// Packaged default Mango configuration. DMS writes its managed fragments under
/// `~/.config/mango/dms/`; this file only provides a sane baseline and the
/// DMS keybindings. It is copied to the user's config on first session start.
pub const MANGO_CONFIG_DEFAULT: &str = r#"# Phoebus default Mango configuration (packaged; copied once, then user-owned).
# DMS manages colors/layout/outputs in ~/.config/mango/dms/*.conf.
source=~/.config/mango/dms/colors.conf
source=~/.config/mango/dms/layout.conf
source=~/.config/mango/dms/outputs.conf
env=QT_QPA_PLATFORM,wayland
env=ELECTRON_OZONE_PLATFORM_HINT,auto
env=QT_QPA_PLATFORMTHEME,gtk3
border_radius=12
borderpx=0
focused_opacity=1.0
unfocused_opacity=0.9
gappih=5
gappiv=5
gappoh=5
gappov=5
shadows=1
shadow_only_floating=1
shadows_size=10
shadows_blur=15
# Master-stack layout defaults (dwm / dwl standard)
new_is_master=0
default_mfact=0.55
default_nmaster=1
tag_num=9
# Tag rules: default to master-and-stack tiling layout
tagrule=id:1,layout_name:tile
tagrule=id:2,layout_name:tile
tagrule=id:3,layout_name:tile
tagrule=id:4,layout_name:tile
tagrule=id:5,layout_name:tile
tagrule=id:6,layout_name:tile
tagrule=id:7,layout_name:tile
tagrule=id:8,layout_name:tile
tagrule=id:9,layout_name:tile
layerrule=noanim:1,layer_name:^dms
windowrule=isfloating:1,appid:^com.danklinux.dms$
windowrule=isfullscreen:1,title:^Install Phoebus OS$
# ===========================================================================
# Standard DWM / DWL Keybindings
# ===========================================================================
# Terminal & Launcher
bind=SUPER+SHIFT,Return,spawn,kitty
bind=SUPER,Return,zoom,
bind=SUPER,p,spawn,dms ipc call spotlight toggle
bind=SUPER,space,spawn,dms ipc call spotlight toggle
# Display resolution shortcuts (instant switch for VMs and external displays)
bind=SUPER+SHIFT,F12,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1920x1080'
bind=SUPER+SHIFT,F11,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1440x900'
bind=SUPER+SHIFT,F10,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1280x768'
bind=SUPER+SHIFT,F9,spawn,sh -c 'out=$(wlr-randr 2>/dev/null | awk "/^[A-Za-z0-9-]+ / {print \$1; exit}"); [ -n "$out" ] && wlr-randr --output "$out" --mode 1024x768'
# Focus navigation (dwm focusstack)
bind=SUPER,j,focusstack,next
bind=SUPER,k,focusstack,prev
bind=SUPER,Down,focusdir,down
bind=SUPER,Up,focusdir,up
bind=SUPER,Left,focusdir,left
bind=SUPER,Right,focusdir,right
# Window movement & swapping (dwm movestack / exchange)
bind=SUPER+SHIFT,j,exchange_client,down
bind=SUPER+SHIFT,k,exchange_client,up
bind=SUPER+SHIFT,Down,exchange_client,down
bind=SUPER+SHIFT,Up,exchange_client,up
bind=SUPER+SHIFT,Left,exchange_client,left
bind=SUPER+SHIFT,Right,exchange_client,right
# Master area sizing (dwm setmfact)
bind=SUPER,h,setmfact,-0.05
bind=SUPER,l,setmfact,+0.05
# Number of master windows (dwm incnmaster)
bind=SUPER,i,incnmaster,+1
bind=SUPER,d,incnmaster,-1
# Window close (dwm killclient: Mod+Shift+c and Mod+Shift+q)
bind=SUPER+SHIFT,c,killclient,
bind=SUPER+SHIFT,q,killclient,
# Layout switching
bind=SUPER,t,setlayout,tile
bind=SUPER,f,togglefullscreen,
bind=SUPER,m,setlayout,monocle
bind=SUPER+SHIFT,space,togglefloating,
bind=SUPER+SHIFT,t,switch_layout,
bind=SUPER+SHIFT,r,reload_config,
bind=SUPER,r,reload_config,
# Tag / Workspace switching (dwm tag navigation)
bind=SUPER,Tab,view,-1
bind=SUPER,1,view,1,0
bind=SUPER,2,view,2,0
bind=SUPER,3,view,3,0
bind=SUPER,4,view,4,0
bind=SUPER,5,view,5,0
bind=SUPER,6,view,6,0
bind=SUPER,7,view,7,0
bind=SUPER,8,view,8,0
bind=SUPER,9,view,9,0
bind=SUPER,0,view,0,0
# Move window to tag (dwm tag)
bind=SUPER+SHIFT,1,tag,1,0
bind=SUPER+SHIFT,2,tag,2,0
bind=SUPER+SHIFT,3,tag,3,0
bind=SUPER+SHIFT,4,tag,4,0
bind=SUPER+SHIFT,5,tag,5,0
bind=SUPER+SHIFT,6,tag,6,0
bind=SUPER+SHIFT,7,tag,7,0
bind=SUPER+SHIFT,8,tag,8,0
bind=SUPER+SHIFT,9,tag,9,0
bind=SUPER+SHIFT,0,tag,0,0
# Multi-tag toggle (dwm toggleview / toggletag)
bind=SUPER+CTRL,1,toggleview,1
bind=SUPER+CTRL,2,toggleview,2
bind=SUPER+CTRL,3,toggleview,3
bind=SUPER+CTRL,4,toggleview,4
bind=SUPER+CTRL,5,toggleview,5
bind=SUPER+CTRL,6,toggleview,6
bind=SUPER+CTRL,7,toggleview,7
bind=SUPER+CTRL,8,toggleview,8
bind=SUPER+CTRL,9,toggleview,9
bind=SUPER+CTRL+SHIFT,1,toggletag,1
bind=SUPER+CTRL+SHIFT,2,toggletag,2
bind=SUPER+CTRL+SHIFT,3,toggletag,3
bind=SUPER+CTRL+SHIFT,4,toggletag,4
bind=SUPER+CTRL+SHIFT,5,toggletag,5
bind=SUPER+CTRL+SHIFT,6,toggletag,6
bind=SUPER+CTRL+SHIFT,7,toggletag,7
bind=SUPER+CTRL+SHIFT,8,toggletag,8
bind=SUPER+CTRL+SHIFT,9,toggletag,9
# Monitor switching (dwm focusmon / tagmon)
bind=SUPER,comma,focusmon,left
bind=SUPER,period,focusmon,right
bind=SUPER+SHIFT,comma,tagmon,left
bind=SUPER+SHIFT,period,tagmon,right
# Mouse bindings (dwm mouse controls: move/resize/toggle float)
mousebind=SUPER,btn_left,moveresize,curmove
mousebind=SUPER,btn_right,moveresize,curresize
mousebind=SUPER,btn_middle,togglefloating,
# ===========================================================================
# Phoebus & DMS Desktop Integration
# ===========================================================================
bind=SUPER,v,spawn,dms ipc call clipboard toggle
bind=SUPER+CTRL,m,spawn,dms ipc call processlist focusOrToggle
bind=SUPER+CTRL,comma,spawn,dms ipc call settings focusOrToggle
bind=SUPER,n,spawn,dms ipc call notifications toggle
bind=SUPER,a,spawn,phoebus-assistant
# Security & Session
bind=SUPER+ALT,l,spawn,dms ipc call lock lock
bind=SUPER+SHIFT,e,quit,
# Audio
bind=NONE,XF86AudioRaiseVolume,spawn,dms ipc call audio increment 3
bind=NONE,XF86AudioLowerVolume,spawn,dms ipc call audio decrement 3
bind=NONE,XF86AudioMute,spawn,dms ipc call audio mute
# Brightness
bind=NONE,XF86MonBrightnessUp,spawn,dms ipc call brightness increment 5
bind=NONE,XF86MonBrightnessDown,spawn,dms ipc call brightness decrement 5
"#;
/// The systemd user target the DMS service is bound to. Using a target means
/// the shell starts and stops with the Mango session and does not run under
/// another desktop.
pub const MANGO_SESSION_TARGET: &str = r#"# Phoebus Mango session target (generated by the installer).
[Unit]
Description=Phoebus Mango + DankMaterialShell session
Requires=graphical-session.target
After=graphical-session.target
"#;
/// The `phoebus-assistant` launcher: launches the Quickshell desktop assistant
/// GUI if available, or falls back to a terminal for `sys ask`.
pub const PHOEBUS_ASSISTANT_SCRIPT: &str = r#"#!/bin/bash
# Open the Phoebus assistant. If graphical environment and quickshell are available,
# launch the desktop assistant GUI. Otherwise fall back to a terminal with `sys ask`.
set -u
if [ -n "${WAYLAND_DISPLAY:-}" ] || [ -n "${DISPLAY:-}" ]; then
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-assistant/shell.qml ]; then
exec quickshell --no-duplicate -c phoebus-assistant
fi
fi
if command -v kitty >/dev/null 2>&1; then
exec kitty --title "Phoebus Assistant" -e bash -lc \
'read -rp "Phoebus assistant request: " r; sudo sys ask "$r"; \
echo; read -rp "Press Enter to close"'
fi
echo "phoebus-assistant: neither quickshell nor kitty is available" >&2
exit 1
"#;
pub const PHOEBUS_ASSISTANT_DESKTOP_ENTRY: &str = r#"[Desktop Entry]
Name=Phoebus Assistant
Comment=AI-first system administration and assistance
Exec=/usr/local/bin/phoebus-assistant
Icon=system-help
Terminal=false
Type=Application
Categories=System;Settings;
Keywords=system;admin;assistant;ai;sys;install;update;
"#;
pub const PHOEBUS_POLKIT_POLICY: &str = r#"
Phoebus OS
https://phoebus.club
system-help
Execute Phoebus system administration plan
Authentication is required to apply the system administration plan
auth_admin
auth_admin
auth_admin_keep
/usr/local/bin/sys
true
"#;
pub fn assistant_desktop_assets() -> Vec<(&'static str, &'static str)> {
vec![
(
"usr/share/polkit-1/actions/club.phoebus.sys.policy",
PHOEBUS_POLKIT_POLICY,
),
(
"etc/xdg/quickshell/phoebus-assistant/shell.qml",
include_str!("../../../../installer/live/desktop/phoebus-assistant/shell.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/AssistantBridge.qml",
include_str!(
"../../../../installer/live/desktop/phoebus-assistant/AssistantBridge.qml"
),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/qmldir",
include_str!("../../../../installer/live/desktop/common/qmldir"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/Theme.qml",
include_str!("../../../../installer/live/desktop/common/Theme.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/Bridge.qml",
include_str!("../../../../installer/live/desktop/common/Bridge.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusButton.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusButton.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusCard.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusCard.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusChip.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusChip.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusChoice.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusChoice.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusCombo.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusCombo.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusEmblem.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusEmblem.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusField.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusField.qml"),
),
(
"etc/xdg/quickshell/phoebus-assistant/Common/PhoebusToggle.qml",
include_str!("../../../../installer/live/desktop/common/PhoebusToggle.qml"),
),
]
}
/// First-login welcome for the installed system (Mango + DankMaterialShell).
///
/// This is distinct from the live ISO's "Install Phoebus OS" welcome, which
/// stays live-only. The installed welcome:
/// - runs once per user (state file `~/.config/phoebus/welcome-seen`) but
/// stays reopenable from the launcher and settings,
/// - never blocks login (background autostart; closing it finishes nothing),
/// - defaults to keeping the working system,
/// - explains the prebuilt fast defaults and offers separate opt-in builds
/// through the existing typed actions (the UI never holds a shell or
/// root; each build shows its review and requires explicit approval).
pub const INSTALLED_WELCOME_QML: &str = r##"// Phoebus first-login welcome (installed system only).
// Mango + DankMaterialShell styling: dark default, Phoebus palette.
// Keyboard: Tab/Shift+Tab moves, Enter activates, Esc closes.
// Layout adapts via anchors + Flickable for small displays.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
id: root
visible: true
title: "Welcome to Phoebus OS"
minimumWidth: 560
minimumHeight: 480
width: 720
height: 600
color: "#14161c"
// Never modal: closing or leaving finishes nothing and blocks nothing.
onClosing: { welcomeBackend.markSeen(); }
Flickable {
anchors.fill: parent
contentWidth: parent.width
contentHeight: column.implicitHeight + 48
clip: true
ScrollBar.vertical: ScrollBar { }
ColumnLayout {
id: column
anchors.horizontalCenter: parent.horizontalCenter
width: Math.min(parent.width - 48, 640)
y: 24
spacing: 12
Label {
text: "Welcome to Phoebus OS"
font.pixelSize: 26
font.bold: true
color: "#f5b942"
focus: true
KeyNavigation.tab: keepButton
}
Label {
text: "Fast by default, yours to tune. Phoebus installed prebuilt, verified applications and a generic kernel to shorten installation. Everything works now; source builds are strictly opt-in."
wrapMode: Text.WordWrap
Layout.fillWidth: true
color: "#d7dae0"
KeyNavigation.tab: keepButton
}
Label {
text: "Your system keeps working while any build runs elsewhere. Compiling is not claimed to make things noticeably faster."
wrapMode: Text.WordWrap
Layout.fillWidth: true
color: "#9aa0ab"
}
GroupBox {
title: "1. Review and selectively build applications from source"
Layout.fillWidth: true
Label {
text: "Firefox, LibreOffice, Calibre and GIMP can be rebuilt from their maintained sources. Shown first: exact packages, expected time, temporary disk, power/network needs, then an explicit approval. The working copy stays until the new build verifies."
wrapMode: Text.WordWrap
width: parent.width
color: "#d7dae0"
}
RowLayout {
Button { id: srcButton; text: "Review source builds"; onClicked: welcomeBackend.openSourceBuilds(); KeyNavigation.tab: kernelButton }
}
}
GroupBox {
title: "2. Build a kernel tuned for this machine"
Layout.fillWidth: true
Label {
text: "Starts from the proven distribution configuration with only supported tuning. A separate boot entry is created and test-booted first; the generic kernel stays installed as the known-good fallback."
wrapMode: Text.WordWrap
width: parent.width
color: "#d7dae0"
}
RowLayout {
Button { id: kernelButton; text: "Review tuned kernel"; onClicked: welcomeBackend.openTunedKernel(); KeyNavigation.tab: keepButton }
}
}
GroupBox {
title: "3. Keep the fast defaults and finish"
Layout.fillWidth: true
RowLayout {
Button { id: keepButton; text: "Keep working system and finish (default)"; highlighted: true; onClicked: { welcomeBackend.markSeen(); root.close(); } KeyNavigation.tab: srcButton }
Button { text: "Close"; onClicked: { welcomeBackend.markSeen(); root.close(); } }
}
}
Label {
text: "Keys: Tab moves, Enter activates, Esc closes. Reopen anytime from the launcher (Phoebus Welcome) or settings."
wrapMode: Text.WordWrap
Layout.fillWidth: true
color: "#9aa0ab"
}
}
}
Shortcut { sequence: "Escape"; onActivated: { welcomeBackend.markSeen(); root.close(); } }
}
"##;
/// Launcher script for the installed welcome. Reopenable; records nothing
/// privileged. The QML talks to `sys --assistant-bridge` for the opt-in
/// actions, so approval and privilege stay in the deterministic broker.
pub const INSTALLED_WELCOME_SCRIPT: &str = r#"#!/bin/bash
# Phoebus first-login welcome (installed system only). Never blocks login:
# it runs in the background and exiting changes nothing.
set -u
SEEN="${XDG_CONFIG_HOME:-$HOME/.config}/phoebus/welcome-seen"
if [ "${1:-}" != "--reopen" ] && [ -f "$SEEN" ]; then
exit 0
fi
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-welcome-installed/shell.qml ]; then
exec quickshell --no-duplicate -c phoebus-welcome-installed "$@"
fi
echo "phoebus-welcome: quickshell is unavailable; reopen from the launcher later" >&2
exit 1
"#;
/// Desktop entry (launcher + settings) for the installed welcome.
pub const INSTALLED_WELCOME_DESKTOP_ENTRY: &str = r#"[Desktop Entry]
Name=Phoebus Welcome
Comment=First-login welcome: fast defaults and opt-in source builds
Exec=/usr/local/bin/phoebus-welcome --reopen
Icon=system-help
Terminal=false
Type=Application
Categories=System;Settings;
Keywords=welcome;setup;phoebus;source;kernel;
"#;
/// Background autostart for the installed welcome. `X-GNOME-Autostart-enabled`
/// only; no blocking, no modal gate — login completes with or without it.
pub const INSTALLED_WELCOME_AUTOSTART: &str = r#"[Desktop Entry]
Name=Phoebus Welcome (first login)
Comment=Show the Phoebus first-login welcome once per user
Exec=/usr/local/bin/phoebus-welcome
Icon=system-help
Terminal=false
Type=Application
X-GNOME-Autostart-enabled=true
NoDisplay=true
"#;
/// Seed content suppressing the upstream DMS first-run dialogs on the
/// installed target, so the user sees exactly one welcome experience (ours).
/// Mirrors the live-medium seeding in `installer/live/build.sh`.
pub fn dms_firstlaunch_seed(version: &str) -> Vec<(&'static str, String)> {
let major_minor = version.split('.').take(2).collect::>().join(".");
vec![
(".config/DankMaterialShell/.firstlaunch", String::new()),
(".config/DankMaterialShell/.changelog-seen", major_minor),
]
}
/// All installed-welcome assets provisioned into the target.
pub fn installed_welcome_assets() -> Vec<(&'static str, &'static str)> {
vec![
(
"etc/xdg/quickshell/phoebus-welcome-installed/shell.qml",
INSTALLED_WELCOME_QML,
),
(
"usr/share/applications/phoebus-welcome.desktop",
INSTALLED_WELCOME_DESKTOP_ENTRY,
),
(
"etc/xdg/autostart/phoebus-welcome.desktop",
INSTALLED_WELCOME_AUTOSTART,
),
]
}
/// A Wayland session entry for `/usr/share/wayland-sessions`.
pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> {
match profile {
DesktopProfile::Mango => Some((
"phoebus-mango.desktop",
"# Phoebus Mango session (generated by the installer).\n\
[Desktop Entry]\n\
Name=Phoebus (Mango + DarkMaterial)\n\
Comment=Mango compositor with DankMaterialShell\n\
Exec=/usr/local/bin/phoebus-session-mango\n\
TryExec=/usr/local/bin/phoebus-session-mango\n\
Type=Application\n\
DesktopNames=mango\n"
.to_string(),
)),
DesktopProfile::None => None,
}
}
/// The installed-system greetd configuration: authenticate, then run the
/// canonical Mango session. There is deliberately **no** `[initial_session]`:
/// the installed system always requires authentication (unlike the live ISO).
pub fn greetd_config(default_cmd: &str) -> String {
format!(
"# /etc/greetd/config.toml - Phoebus login (generated by the installer).\n\
# Authentication is always required; the live ISO uses a separate\n\
# autologin configuration.\n\
[terminal]\n\
vt = 7\n\
\n\
[default_session]\n\
command = \"tuigreet --time --remember --remember-session --sessions /usr/share/wayland-sessions --cmd {default_cmd}\"\n\
user = \"greeter\"\n"
)
}
/// The live-ISO greetd configuration: a live-only automatic login into the
/// desktop, with a greeter fallback. This must never be written to an installed
/// system.
pub fn greetd_config_live(live_user: &str, session_cmd: &str) -> String {
format!(
"# /etc/greetd/config.toml - Phoebus live session (LIVE ONLY).\n\
# Automatic login is intentional on the live medium and is not copied\n\
# to an installed system.\n\
[terminal]\n\
vt = 7\n\
\n\
[initial_session]\n\
command = \"{session_cmd}\"\n\
user = \"{live_user}\"\n\
\n\
[default_session]\n\
command = \"tuigreet --time --sessions /usr/share/wayland-sessions --cmd {session_cmd}\"\n\
user = \"greeter\"\n"
)
}
/// The session command used as the default desktop for a profile.
pub fn default_session_command(_profile: DesktopProfile) -> &'static str {
"/usr/local/bin/phoebus-session-mango"
}
/// The live ISO's unprivileged user.
pub const LIVE_USER: &str = "phoebus";
/// The live medium's passwordless privilege policy.
///
/// The recovery console keeps full root through the **password-authenticated**
/// `sudo` group (the live-only `phoebus`/`phoebus` credential, printed in
/// `installer/live/README.md`), so a serial or VT operator can still repair a
/// broken live session. Unattended escalation is limited to the two typed
/// brokers — the installer and `sys` — which validate actions before doing
/// anything. `systemctl` power actions are included because the welcome and
/// installer UIs offer them. There is no `ALL` command, no `sh -c`, and no
/// wildcard: a permitted program cannot become a general shell.
pub const LIVE_SUDOERS: &str = "\
# Phoebus live-medium privilege policy (generated).
# The recovery console authenticates with the live-only password; only the
# typed brokers below can escalate without a prompt. Do not add ALL or
# wildcards here.
phoebus ALL=(root) NOPASSWD: /usr/local/bin/phoebus-installer
phoebus ALL=(root) NOPASSWD: /usr/local/bin/sys
phoebus ALL=(root) NOPASSWD: /usr/bin/systemctl poweroff
phoebus ALL=(root) NOPASSWD: /usr/bin/systemctl reboot
";
/// `phoebus-nvidia-load`: live-only. It runs before the graphical session and
/// asks the installer for a deterministic decision based on the actual PCI
/// display devices and the bundled branch's capabilities. Systems without an
/// NVIDIA GPU keep the in-tree driver; an unsupported GPU explicitly binds
/// `nouveau`; fail-safe graphics loads nothing. A failed accelerated load is a
/// fallback, never a failed unit.
pub const PHOEBUS_NVIDIA_LOAD_SCRIPT: &str = r#"#!/bin/bash
# Select the live medium's display driver before greetd/Mango starts.
#
# `phoebus-installer --live-gpu-plan` classifies every PCI display controller
# and compares it with the bundled branch, then prints:
# action=load-nvidia -> load the bundled accelerated stack
# action=nouveau-fallback-> explicitly bind the in-tree nouveau driver
# action=no-device -> no NVIDIA GPU; leave auto-detection alone
# action=disabled -> fail-safe boot; load no NVIDIA module
#
# `blacklist nouveau` in /etc/modprobe.d stops nouveau *auto-binding* a
# supported GPU; it does not block an explicit `modprobe nouveau`, which is
# exactly what the fallback path uses. Debian's nvidia-kernel-dkms maps the
# upstream module names used here onto nvidia-current*.
set -u
BIN=/usr/local/bin/phoebus-installer
log() { logger -t phoebus-nvidia -- "$*" 2>/dev/null || true; }
plan="$("$BIN" --live-gpu-plan 2>/dev/null || true)"
action="$(printf '%s\n' "$plan" | sed -n 's/^action=//p' | head -n1)"
case "$action" in
load-nvidia)
if modprobe nvidia-drm; then
modprobe nvidia-uvm || log "nvidia-uvm did not load (not fatal)"
log "loaded the NVIDIA accelerated driver: $(printf '%s' "$plan" | tr '\n' ';')"
exit 0
fi
log "NVIDIA initialisation failed; falling back to nouveau"
modprobe nouveau || log "nouveau did not load either; run phoebus-gpu-report"
;;
nouveau-fallback)
log "NVIDIA GPU is not supported by the bundled branch; using nouveau: $(printf '%s' "$plan" | tr '\n' ';')"
modprobe nouveau || log "nouveau did not load; run phoebus-gpu-report"
;;
disabled)
log "fail-safe graphics requested; not loading the NVIDIA stack"
;;
*)
log "no NVIDIA display device; leaving driver auto-detection in charge"
;;
esac
exit 0
"#;
/// `phoebus-nvidia.service`: load the driver before greetd/Mango.
pub const PHOEBUS_NVIDIA_SERVICE: &str = r#"[Unit]
Description=Load the NVIDIA accelerated driver (Phoebus live)
Documentation=man:nvidia(4)
After=systemd-modules-load.service
Before=display-manager.service greetd.service
# Recovery intent is authoritative: the fail-safe entry sets
# phoebus.nvidia=off, so the unit does not even run there.
ConditionKernelCommandLine=!phoebus.nvidia=off
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/phoebus-nvidia-load
TimeoutStartSec=30
[Install]
WantedBy=multi-user.target
"#;
/// `phoebus-gpu-report`: live diagnostics when NVIDIA initialisation is
/// suspect. Read-only.
pub const PHOEBUS_GPU_REPORT_SCRIPT: &str = r#"#!/bin/bash
# Phoebus GPU diagnostics: what claimed the display, and did nvidia_drm come up?
set -u
echo "== display devices =="
lspci -nnk 2>/dev/null | grep -A3 -Ei 'VGA|3D controller|Display controller' || echo "(lspci unavailable)"
echo
echo "== loaded GPU modules =="
grep -E 'nvidia|nouveau' /proc/modules 2>/dev/null || echo "(neither nvidia nor nouveau is loaded)"
echo
echo "== nvidia_drm modeset =="
cat /sys/module/nvidia_drm/parameters/modeset 2>/dev/null || echo "(nvidia_drm not loaded)"
echo
echo "== nvidia-smi =="
nvidia-smi 2>&1 | head -20 || true
echo
echo "== recent kernel GPU messages =="
dmesg 2>/dev/null | grep -Ei 'nvidia|nouveau|drm' | tail -30 \
|| echo "(dmesg needs privileges; try: sudo dmesg | grep -Ei 'nvidia|nouveau|drm')"
"#;
/// A named desktop asset, so the live ISO build and the installer use exactly
/// the same configuration and session scripts. `None` for an unknown name.
pub fn desktop_asset(name: &str) -> Option {
let default_cmd = default_session_command(DesktopProfile::Mango);
let live_cmd = "/usr/local/bin/phoebus-session-mango";
Some(match name {
"session-mango" => PHOEBUS_MANGO_SESSION_SCRIPT.to_string(),
"assistant" => PHOEBUS_ASSISTANT_SCRIPT.to_string(),
"install" => PHOEBUS_INSTALL_SCRIPT.to_string(),
"welcome" => PHOEBUS_WELCOME_SCRIPT.to_string(),
"mango-config" => MANGO_CONFIG_DEFAULT.to_string(),
"mango-session-target" => MANGO_SESSION_TARGET.to_string(),
"install-desktop" => PHOEBUS_INSTALL_DESKTOP_ENTRY.to_string(),
"greetd-installed" => greetd_config(default_cmd),
"greetd-live" => greetd_config_live(LIVE_USER, live_cmd),
// Live-only privilege policy (scoped, never NOPASSWD: ALL).
"live-sudoers" => LIVE_SUDOERS.to_string(),
// Live-only NVIDIA driver loading and diagnostics.
"nvidia-load" => PHOEBUS_NVIDIA_LOAD_SCRIPT.to_string(),
"nvidia-service" => PHOEBUS_NVIDIA_SERVICE.to_string(),
"gpu-report" => PHOEBUS_GPU_REPORT_SCRIPT.to_string(),
"wayland-session-mango" => wayland_session_entry(DesktopProfile::Mango)?.1,
// The brand system lives in `brand`; route the shared `--emit-asset`
// plumbing through it so the live build has one source of assets.
_ => return crate::brand::brand_asset(name),
})
}
/// `phoebus-install`: open the graphical installer frontend, falling back to
/// the deterministic TUI/CLI. It never starts a destructive operation by
/// itself: the plan, disk protection, AI requirement, credential handling and
/// the ERASE confirmation all stay in force. A second invocation never opens a
/// duplicate installer session.
pub const PHOEBUS_INSTALL_SCRIPT: &str = r#"#!/bin/bash
# Open the Phoebus installer. This only launches the installer UI; the user
# still reviews the plan, supplies credentials and confirms ERASE.
set -u
# Prevent duplicate installer sessions. Quickshell's --no-duplicate also
# guards this, but the check lets us tell the user why nothing opened.
if pgrep -f "quickshell.*phoebus-install" >/dev/null 2>&1; then
echo "The Phoebus installer is already open." >&2
exit 0
fi
# The graphical installer is the primary path; it needs a Wayland session.
if [ "${XDG_SESSION_TYPE:-}" = "wayland" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; then
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-install/shell.qml ]; then
pkill -f "quickshell.*phoebus-welcome" 2>/dev/null || true
exec quickshell --no-duplicate -c phoebus-install
fi
fi
# Deterministic fallback (TUI, then CLI) works with no model and no Wayland.
conf="/etc/phoebus/install.conf"
args=()
[ -f "$conf" ] && args+=(--config "$conf")
installer=""
for candidate in /usr/local/bin/phoebus-installer phoebus-installer; do
if command -v "$candidate" >/dev/null 2>&1; then
installer="$candidate"
break
fi
done
if [ -z "$installer" ]; then
echo "phoebus-install: installer not found" >&2
exit 1
fi
# Re-entrant wrapper: the inner invocation (inside the terminal) just runs.
if [ "${1:-}" = "--in-terminal" ]; then
"$installer" "${args[@]}"
rc=$?
echo
read -rp "Press Enter to close" _ || true
exit "$rc"
fi
if command -v kitty >/dev/null 2>&1; then
exec kitty --title "Install Phoebus OS" -e "$0" --in-terminal
fi
if [ "$(id -u)" -eq 0 ]; then
exec "$installer" "${args[@]}"
else
exec sudo -n "$installer" "${args[@]}"
fi
"#;
/// `phoebus-welcome`: open (or focus, via the single-instance guard) the live
/// welcome window. Only installed on the live medium.
pub const PHOEBUS_WELCOME_SCRIPT: &str = r#"#!/bin/bash
# Live-medium welcome and installation launcher.
set -u
if pgrep -f "quickshell.*phoebus-welcome" >/dev/null 2>&1; then
exit 0
fi
if command -v quickshell >/dev/null 2>&1 \
&& [ -f /etc/xdg/quickshell/phoebus-welcome/shell.qml ]; then
exec quickshell --no-duplicate -c phoebus-welcome
fi
echo "phoebus-welcome: quickshell or the welcome config is missing" >&2
exit 1
"#;
/// The application entry that makes the installer discoverable in the desktop
/// launcher ("Install Phoebus OS"). It is live-medium only.
pub const PHOEBUS_INSTALL_DESKTOP_ENTRY: &str = "\
[Desktop Entry]\n\
Type=Application\n\
Name=Install Phoebus OS\n\
GenericName=System installer\n\
Comment=Install Phoebus OS to disk\n\
Exec=/usr/local/bin/phoebus-install\n\
TryExec=/usr/local/bin/phoebus-install\n\
Icon=phoebus\n\
Terminal=false\n\
Categories=System;Settings;\n\
Keywords=install;phoebus;setup;\n";
/// Btrfs mount options, matching the proven behavior.
pub fn btrfs_mount_opts(compress: &str, ssd: bool) -> String {
let mut opts = format!("noatime,compress={compress},space_cache=v2");
if ssd {
opts.push_str(",ssd");
}
opts
}
// ---------------------------------------------------------------------------
// fstab / crypttab / cmdline
// ---------------------------------------------------------------------------
pub fn fstab(
config: &InstallConfig,
root_source: &str,
efi_uuid: Option<&str>,
btrfs_opts: &str,
) -> String {
fstab_with_subvols(
config,
root_source,
efi_uuid,
btrfs_opts,
&config.storage.root_subvolume(),
"@var",
)
}
/// As `fstab`, but for an explicit root and `/var` subvolume. A rollback
/// rewrites the restored root's fstab so it mounts its own generation rather
/// than the name the snapshot happened to be captured under.
pub fn fstab_with_subvols(
config: &InstallConfig,
root_source: &str,
efi_uuid: Option<&str>,
btrfs_opts: &str,
root_subvol: &str,
var_subvol: &str,
) -> String {
let mut o = String::new();
o.push_str(&format!("# /etc/fstab: {}\n", config.system.distro_name));
o.push_str("# Generated by the installer. Use `findmnt --verify` to check.\n#\n");
o.push_str("# \t\t\t\t\t\n");
if let Some(uuid) = efi_uuid {
o.push_str(&format!(
"UUID={uuid}\t{}\tvfat\tumask=0077,shortname=winnt\t0\t2\n",
config.storage.efi_mount
));
}
for (subvol, mountpoint, pass) in [
(root_subvol, "/", 1),
("@home", "/home", 2),
(var_subvol, "/var", 2),
("@snapshots", "/.snapshots", 2),
("@swap", "/swap", 2),
] {
o.push_str(&format!(
"{root_source}\t{mountpoint}\tbtrfs\t{btrfs_opts},subvol={subvol}\t0\t{pass}\n"
));
}
o.push_str("/swap/swapfile\tnone\tswap\tdefaults\t0\t0\n");
o
}
pub fn crypttab(name: &str, part_uuid: &str) -> String {
let mut o = String::new();
o.push_str("# /etc/crypttab: unlock the root volume at boot.\n");
o.push_str("# \t\t\t\n");
o.push_str(&format!("{name} UUID={part_uuid} none luks,discard\n"));
o
}
/// The kernel command line.
///
/// `luks_uuid` is required when encryption is on; `root_source` is used for an
/// unencrypted Btrfs root (a UUID= reference).
pub fn kernel_cmdline(
config: &InstallConfig,
luks_uuid: Option<&str>,
root_source: &str,
) -> Result {
kernel_cmdline_with_root(
config,
luks_uuid,
root_source,
&config.storage.root_subvolume(),
)
}
/// As `kernel_cmdline`, but selecting an explicit root subvolume. The explicit
/// `rootflags=subvol=` always wins over the Btrfs default subvolume, so a
/// rollback must rewrite it here as well as in the boot loader entry.
pub fn kernel_cmdline_with_root(
config: &InstallConfig,
luks_uuid: Option<&str>,
root_source: &str,
root_subvol: &str,
) -> Result {
let mut cmdline = String::new();
if config.is_encrypted() {
let uuid = luks_uuid.ok_or_else(|| "missing LUKS UUID".to_string())?;
let name = &config.encryption.name;
// rd.luks.name== makes dracut/systemd create the mapper
// under the configured name; rd.luks.uuid alone yields luks-.
cmdline.push_str(&format!("rd.luks.name={uuid}={name} "));
cmdline.push_str(&format!("root=/dev/mapper/{name} "));
} else {
if root_source.is_empty() {
return Err("unencrypted cmdline requires an explicit root source".into());
}
cmdline.push_str(&format!("root={root_source} "));
}
cmdline.push_str(&format!(
"rootfstype=btrfs rootflags=subvol={root_subvol} rw quiet"
));
if !config.kernel.console.is_empty() {
cmdline.push(' ');
cmdline.push_str(&config.kernel.console);
}
Ok(cmdline)
}
pub fn locale_gen_line(locale: &str) -> String {
format!("{locale} UTF-8\n")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{DesktopProfile, Encryption, InstallConfig};
use crate::hardware::CpuInfo;
#[test]
fn base_packages_include_storage_tools() {
let pkgs = base_packages();
assert!(pkgs.contains(&"sys-fs/cryptsetup"));
assert!(pkgs.contains(&"sys-fs/btrfs-progs"));
assert!(pkgs.contains(&"net-misc/networkmanager"));
}
#[test]
fn kernel_extras_follow_cpu_features() {
let cpu = CpuInfo {
features: vec!["vmx".into()],
..Default::default()
};
let pkgs = kernel_extra_packages(&cpu);
assert!(pkgs.contains(&"sys-kernel/linux-firmware"));
assert!(pkgs.contains(&"sys-firmware/intel-microcode"));
assert!(!pkgs.contains(&"sys-firmware/amd-ucode"));
}
#[test]
fn fstab_mounts_all_subvolumes_including_swap() {
let cfg = InstallConfig::default();
let text = fstab(
&cfg,
"/dev/mapper/cryptroot",
Some("EFI-UUID"),
"noatime,compress=zstd:3,space_cache=v2",
);
assert!(text.contains("UUID=EFI-UUID\t/efi\tvfat"));
assert!(text.contains("\t/\tbtrfs\t"));
assert!(text.contains("subvol=@home"));
assert!(text.contains("subvol=@var"));
assert!(text.contains("subvol=@snapshots"));
assert!(text.contains("subvol=@swap"));
assert!(text.contains("/swap/swapfile\tnone\tswap"));
}
#[test]
fn crypttab_uses_partition_uuid() {
let text = crypttab("cryptroot", "0000-1111");
assert!(text.contains("cryptroot UUID=0000-1111 none luks,discard"));
}
#[test]
fn cmdline_uses_rd_luks_name() {
let cfg = InstallConfig::default();
let cmd = kernel_cmdline(&cfg, Some("0000-1111"), "").unwrap();
assert!(cmd.contains("rd.luks.name=0000-1111=cryptroot"));
assert!(cmd.contains("root=/dev/mapper/cryptroot"));
assert!(!cmd.contains("rd.luks.uuid="));
assert!(cmd.contains("console=tty0"));
}
#[test]
fn install_conf_has_uki_generator_none() {
let text = install_conf();
assert!(text.contains("layout=bls"));
assert!(text.contains("initrd_generator=dracut"));
assert!(text.contains("uki_generator=none"));
}
#[test]
fn desktop_includes_portals_for_flatpak_and_wayland() {
let pkgs = desktop_packages(DesktopProfile::Mango);
assert!(pkgs.contains(&"sys-apps/xdg-desktop-portal"));
assert!(pkgs.contains(&"sys-apps/xdg-desktop-portal-gtk"));
assert!(pkgs.contains(&"gui-libs/xdg-desktop-portal-wlr"));
assert!(desktop_packages(DesktopProfile::None).is_empty());
}
#[test]
fn desktop_none_has_no_x_use_block() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::None;
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
assert!(!text.contains("x11-libs/cairo X"));
cfg.desktop.profile = DesktopProfile::Mango;
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
assert!(text.contains("x11-libs/cairo X"));
assert!(text.contains("media-libs/libglvnd X"));
assert!(text.contains("sys-fs/btrfs-progs -man"));
assert!(text.contains("sys-fs/cryptsetup -man"));
assert!(text.contains("dev-python/pillow -truetype"));
}
#[test]
fn make_conf_does_not_globally_enable_testing() {
let cfg = InstallConfig::default();
let hw = crate::hardware::HardwareReport::default();
let text = make_conf(&cfg, &hw);
assert!(text.contains("ACCEPT_KEYWORDS=\"amd64\""));
assert!(!text.contains("~amd64"));
assert!(text.contains("--backtrack=100"));
}
#[test]
fn makeopts_caps_explicit_jobs_by_memory() {
assert_eq!(makeopts(8, 8192, None), "-j4 -l8");
assert_eq!(makeopts(8, 8192, Some(2)), "-j2 -l8");
assert_eq!(makeopts(8, 8192, Some(99)), "-j4 -l8");
assert_eq!(makeopts(0, 0, None), "-j1 -l4");
}
#[test]
fn package_use_is_clean_and_keeps_required_flags() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
// Required boot/encryption/session flags stay.
assert!(text.contains("sys-apps/systemd boot policykit cryptsetup"));
assert!(text.contains("sys-kernel/installkernel dracut systemd systemd-boot"));
assert!(text.contains("sys-fs/squashfs-tools lzma lzo"));
// BLS does not need the `uki` flag, and the empty wireplumber line and
// the duplicate pipewire line are gone.
assert!(!text.contains(" systemd-boot uki"));
assert!(!text.contains("media-video/wireplumber\n"));
assert_eq!(text.matches("media-video/pipewire").count(), 1);
assert!(text.contains("media-video/pipewire sound-server systemd"));
}
#[test]
fn package_use_appends_validated_entries() {
let mut cfg = InstallConfig::default();
cfg.packages.package_use.push(crate::config::PackageUse {
atom: "www-client/firefox".into(),
flag: "wayland".into(),
enabled: false,
});
let text = package_use(&cfg, &crate::hardware::HardwareReport::default());
assert!(text.contains("www-client/firefox -wayland"));
}
#[test]
fn binhost_selection_follows_profile() {
assert_eq!(binhost_for_profile(PROFILE_SYSTEMD_MINIMAL), BINHOST_OPENRC);
assert_eq!(
binhost_for_profile("default/linux/amd64/23.0/hardened/systemd"),
BINHOST_HARDENED
);
let mut cfg = InstallConfig::default();
cfg.stage3.binhost_uri.clear();
cfg.stage3.gentoo_profile = "default/linux/amd64/23.0/hardened/systemd".into();
assert_eq!(resolved_binhost_uri(&cfg), BINHOST_HARDENED);
cfg.stage3.binhost_uri = "https://example.invalid/binpkgs".into();
assert_eq!(
resolved_binhost_uri(&cfg),
"https://example.invalid/binpkgs"
);
assert!(binrepos_conf(&cfg).contains("verify-signature = true"));
}
#[test]
fn desktop_selects_desktop_systemd_profile() {
let mut cfg = InstallConfig::default();
// The default profile is a desktop, so it selects the desktop profile.
assert_eq!(cfg.desktop.profile, DesktopProfile::Mango);
assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_DESKTOP);
// An explicit `none` keeps the minimal systemd profile.
cfg.desktop.profile = DesktopProfile::None;
assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_MINIMAL);
// An explicit non-default Gentoo profile is respected.
cfg.stage3.gentoo_profile = "default/linux/amd64/23.0/hardened/systemd".into();
assert_eq!(
selected_profile(&cfg),
"default/linux/amd64/23.0/hardened/systemd"
);
}
#[test]
fn services_deduplicated() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
let svcs = target_services(&cfg);
assert!(svcs.contains(&"NetworkManager".to_string()));
assert!(svcs.contains(&"bluetooth".to_string()));
let count = svcs.iter().filter(|s| *s == "NetworkManager").count();
assert_eq!(count, 1);
}
#[test]
fn encrypted_cmdline_requires_uuid() {
let cfg = InstallConfig::default();
assert_eq!(cfg.encryption.mode, Encryption::Luks2);
assert!(kernel_cmdline(&cfg, None, "").is_err());
}
#[test]
fn mango_profile_selects_guru_stack() {
let pkgs = desktop_packages(DesktopProfile::Mango);
assert!(pkgs.contains(&"gui-wm/mangowm"));
assert!(pkgs.contains(&"gui-apps/dankmaterialshell"));
assert!(pkgs.contains(&"gui-apps/danksearch"));
assert!(pkgs.contains(&"dev-vcs/git"));
// Standalone dwl and helpers must not be present.
assert!(!pkgs.contains(&"gui-wm/dwl"));
assert!(!pkgs.contains(&"gui-apps/waybar"));
assert!(!pkgs.contains(&"gui-apps/wofi"));
assert!(!pkgs.contains(&"gui-apps/mako"));
assert!(!pkgs.contains(&"gui-apps/swaybg"));
assert!(!pkgs.contains(&"gui-apps/swayidle"));
assert!(!pkgs.contains(&"gui-apps/swaylock"));
// Portals and the shared Wayland stack are present.
assert!(pkgs.contains(&"sys-apps/xdg-desktop-portal-gtk"));
assert!(pkgs.contains(&"gui-libs/xdg-desktop-portal-wlr"));
// An explicit Mango profile selects the desktop/systemd Gentoo profile.
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_DESKTOP);
assert!(uses_guru(&cfg));
assert!(target_services(&cfg).contains(&"bluetooth".to_string()));
}
#[test]
fn mango_keywords_are_scoped_not_global() {
let text = accept_keywords_mango();
for atom in [
"gui-wm/mangowm",
"gui-apps/dankmaterialshell",
"gui-apps/quickshell",
"gui-libs/scenefx",
"media-gfx/swayimg",
"gui-apps/matugen",
"dev-cpp/cpptrace",
"dev-libs/libdwarf",
] {
assert!(text.contains(atom), "missing {atom}");
}
assert!(!text.contains("*/*"));
// No bare global keyword line; `~amd64` may only appear in comments.
assert!(!text.lines().any(|l| l.trim() == "~amd64"));
assert!(!text.contains("ACCEPT_KEYWORDS"));
let repos = guru_repos_conf();
assert!(repos.contains("[guru]"));
assert!(repos.contains("sync-type = git"));
assert!(repos.contains("anongit.gentoo.org"));
}
#[test]
fn mango_session_contract() {
let script = PHOEBUS_MANGO_SESSION_SCRIPT;
// Exactly one compositor and one shell.
assert!(script.contains("mango &"));
assert!(script.contains("dms run"));
assert!(script.contains("mango-session.target"));
// The dwl helpers must never start in the Mango session.
for helper in ["waybar", "mako", "swaybg", "swayidle", "swaylock"] {
assert!(
!script.contains(helper),
"Mango session must not start the dwl helper {helper}"
);
}
// User config is seeded, never overwritten.
assert!(script.contains("if [ ! -e \"$mango_conf\" ]"));
assert!(script.contains("dbus-update-activation-environment --systemd"));
assert!(script.contains("wait \"$MANGO_PID\""));
// WAYLAND_DISPLAY must not be set before the compositor starts, or
// wlroots selects its nested Wayland backend instead of DRM.
let mango_at = script.find("mango &").unwrap();
let wayland_at = script.find("WAYLAND_DISPLAY=").unwrap();
assert!(
wayland_at > mango_at,
"WAYLAND_DISPLAY must only be set after mango starts"
);
let config = MANGO_CONFIG_DEFAULT;
assert!(config.contains("dms ipc call lock lock"));
assert!(config.contains("dms ipc call spotlight toggle"));
assert!(config.contains("XF86AudioRaiseVolume"));
assert!(config.contains("XF86MonBrightnessDown"));
assert!(config.contains("phoebus-assistant"));
assert!(config.contains("source=~/.config/mango/dms/"));
assert!(config.contains("focusstack,next"));
assert!(config.contains("focusstack,prev"));
assert!(config.contains("zoom,"));
assert!(config.contains("setmfact,-0.05"));
assert!(config.contains("setmfact,+0.05"));
assert!(config.contains("killclient,"));
assert!(config.contains("view,1,0"));
assert!(config.contains("tag,1,0"));
assert!(config.contains("setlayout,tile"));
assert!(config.contains("togglefloating,"));
let (name, entry) = wayland_session_entry(DesktopProfile::Mango).unwrap();
assert_eq!(name, "phoebus-mango.desktop");
assert!(entry.contains("Exec=/usr/local/bin/phoebus-session-mango"));
}
#[test]
fn installed_login_authenticates_and_defaults_to_mango() {
let cfg = greetd_config("/usr/local/bin/phoebus-session-mango");
assert!(
cfg.parse::().is_ok(),
"greetd_config must produce valid TOML"
);
assert!(cfg.contains("[terminal]"));
assert!(cfg.contains("vt = 7"));
assert!(cfg.contains("[default_session]"));
// The installed system must never autologin.
assert!(!cfg.contains("[initial_session]"));
assert!(cfg.contains("tuigreet"));
assert!(cfg.contains("--sessions /usr/share/wayland-sessions"));
assert!(cfg.contains("--cmd /usr/local/bin/phoebus-session-mango"));
// The live configuration is separate and does autologin.
let live = greetd_config_live("phoebus", "/usr/local/bin/phoebus-session-mango");
assert!(
live.parse::().is_ok(),
"greetd_config_live must produce valid TOML"
);
assert!(live.contains("[initial_session]"));
assert!(live.contains("user = \"phoebus\""));
assert!(live.contains("[default_session]"));
assert_eq!(
default_session_command(DesktopProfile::Mango),
"/usr/local/bin/phoebus-session-mango"
);
assert_eq!(
default_session_command(DesktopProfile::None),
"/usr/local/bin/phoebus-session-mango"
);
}
#[test]
fn install_launcher_is_discoverable_but_not_automatic() {
assert!(PHOEBUS_INSTALL_DESKTOP_ENTRY.contains("Name=Install Phoebus"));
assert!(PHOEBUS_INSTALL_DESKTOP_ENTRY.contains("Exec=/usr/local/bin/phoebus-install"));
// It may run the installer UI, never an unattended destructive install.
assert!(!PHOEBUS_INSTALL_SCRIPT.contains("--yes"));
assert!(!PHOEBUS_INSTALL_SCRIPT.contains("--install"));
assert!(!PHOEBUS_INSTALL_SCRIPT.contains("--no-ai"));
assert!(PHOEBUS_INSTALL_SCRIPT.contains("sudo -n"));
}
#[test]
fn desktop_assets_are_shared_between_live_and_installed() {
assert!(desktop_asset("session-mango").unwrap().contains("dms run"));
assert!(desktop_asset("mango-config")
.unwrap()
.contains("dms ipc call"));
// The live and installed greetd configs differ only in autologin.
assert!(desktop_asset("greetd-live")
.unwrap()
.contains("[initial_session]"));
assert!(!desktop_asset("greetd-installed")
.unwrap()
.contains("[initial_session]"));
assert!(desktop_asset("greetd-installed")
.unwrap()
.contains("phoebus-session-mango"));
assert!(desktop_asset("wayland-session-dwl").is_none());
assert!(desktop_asset("session-dwl").is_none());
assert!(desktop_asset("install-desktop")
.unwrap()
.contains("Install Phoebus"));
assert!(desktop_asset("does-not-exist").is_none());
}
#[test]
fn live_sudoers_is_scoped_and_valid() {
let sudoers = desktop_asset("live-sudoers").unwrap();
assert!(sudoers.contains("/usr/local/bin/phoebus-installer"));
assert!(sudoers.contains("/usr/local/bin/sys"));
assert!(sudoers.contains("systemctl poweroff"));
// The unattended rule must never be a general root escape.
assert!(!sudoers.contains("NOPASSWD: ALL"), "{sudoers}");
assert!(!sudoers.contains("(ALL)"), "{sudoers}");
assert!(!sudoers.contains('*'), "{sudoers}");
assert!(sudoers.ends_with('\n'));
// `visudo` is the authority on syntax; validate when the host has it.
let Ok(mut child) = std::process::Command::new("visudo")
.args(["-cf", "/dev/stdin"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
else {
return;
};
{
use std::io::Write;
if let Some(stdin) = child.stdin.as_mut() {
let _ = stdin.write_all(sudoers.as_bytes());
}
}
if let Ok(out) = child.wait_with_output() {
assert!(
out.status.success(),
"visudo rejected the live policy: {}",
String::from_utf8_lossy(&out.stderr)
);
}
}
#[test]
fn live_nvidia_assets_are_bounded_and_ordered_before_greetd() {
let load = desktop_asset("nvidia-load").unwrap();
// The decision comes from the installer, not a vendor-name grep.
assert!(load.contains("--live-gpu-plan"));
assert!(load.contains("nouveau-fallback"));
assert!(load.contains("modprobe nvidia-drm"));
// A failed accelerated load must not fail the boot unit.
assert!(!load.contains("exit 1"));
let service = desktop_asset("nvidia-service").unwrap();
assert!(service.contains("Before=display-manager.service greetd.service"));
assert!(service.contains("ConditionKernelCommandLine=!phoebus.nvidia=off"));
assert!(service.contains("ExecStart=/usr/local/bin/phoebus-nvidia-load"));
let report = desktop_asset("gpu-report").unwrap();
assert!(report.contains("nvidia-smi"));
assert!(report.contains("nvidia_drm"));
}
fn nvidia_hw(id: &str) -> HardwareReport {
let mut hw = HardwareReport::default();
hw.gpus.push(crate::hardware::GpuInfo {
vendor: GpuVendor::Nvidia,
description: id.into(),
pci_id: Some(id.into()),
pci_address: None,
});
hw
}
#[test]
fn nvidia_turing_uses_open_modules_and_scoped_keywords() {
let cfg = InstallConfig::default();
let hw = nvidia_hw("10de:1e04");
assert_eq!(video_cards(&hw), "nvidia");
let use_text = package_use(&cfg, &hw);
assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel kernel-open"));
// No NVIDIA mask on Turing, but the workstation scopes (TLP conflict,
// Brave beta/nightly) still apply on the default Mango profile.
let mask = package_mask(&cfg, &hw);
assert!(!mask.contains("nvidia-drivers-581"));
assert!(mask.contains("sys-power/tlp"));
assert!(mask.contains("www-client/brave-browser-beta"));
assert!(accept_keywords_policy(&hw).contains("x11-drivers/nvidia-drivers ~amd64"));
// The generic initramfs must not force modules that do not exist yet;
// the NVIDIA fragment is written once the driver is installed.
assert!(!dracut_conf(&cfg).contains("force_drivers"));
let nvidia = nvidia_dracut_conf(&hw).expect("nvidia dracut fragment");
assert!(nvidia.contains("force_drivers+="));
assert!(nvidia.contains("nvidia_drm"));
}
#[test]
fn nvidia_pascal_uses_proprietary_and_is_capped_after_580() {
let cfg = InstallConfig::default();
let hw = nvidia_hw("10de:1b81");
let use_text = package_use(&cfg, &hw);
assert!(use_text.contains("x11-drivers/nvidia-drivers dist-kernel -kernel-open"));
let mask = package_mask(&cfg, &hw);
assert!(mask.contains(">=x11-drivers/nvidia-drivers-581"));
assert!(mask.contains("sys-power/tlp"));
assert!(mask.contains("www-client/brave-browser-beta"));
}
#[test]
fn nvidia_kepler_uses_nouveau_not_a_claim_of_nvidia() {
let cfg = InstallConfig::default();
let hw = nvidia_hw("10de:0fc0");
assert_eq!(video_cards(&hw), "nouveau");
assert!(!package_use(&cfg, &hw).contains("nvidia-drivers"));
let mask = package_mask(&cfg, &hw);
assert!(!mask.contains("nvidia-drivers-581"));
assert!(mask.contains("sys-power/tlp"));
assert!(!accept_keywords_policy(&hw).contains("nvidia-drivers"));
assert!(nvidia_dracut_conf(&hw).is_none());
assert!(!dracut_conf(&cfg).contains("nvidia"));
}
#[test]
fn hybrid_nvidia_keeps_the_integrated_gpu_in_video_cards() {
let mut hw = nvidia_hw("10de:2482");
hw.gpus.push(crate::hardware::GpuInfo {
vendor: GpuVendor::Intel,
description: "Intel UHD".into(),
pci_id: Some("8086:9a60".into()),
pci_address: None,
});
let cards = video_cards(&hw);
assert!(cards.contains("nvidia"));
assert!(cards.contains("intel"));
}
#[test]
fn workstation_defaults_resolve_every_requested_application() {
let pkgs = desktop_packages(DesktopProfile::Mango);
// Every requested application resolves to an exact atom; nothing is
// silently omitted or substituted.
for atom in [
"app-editors/emacs",
"app-office/libreoffice-bin",
"media-gfx/swayimg",
"media-video/mpv",
"app-misc/fastfetch",
"sys-process/htop",
"app-editors/neovim",
"app-text/zathura",
"app-text/zathura-pdf-mupdf",
"app-editors/nano",
"www-client/firefox-bin",
"www-client/brave-browser",
"mail-client/thunderbird",
"net-p2p/transmission",
"media-sound/pavucontrol",
"net-print/cups",
"gnome-extra/nemo",
"sci-calculators/qalculate-gtk",
"net-irc/hexchat",
"net-misc/openssh",
] {
assert!(pkgs.contains(&atom), "missing workstation atom {atom}");
}
// Fast defaults: -bin atoms replace the source builds; Calibre and
// GIMP ship as system-wide Flatpaks, never as duplicate Portage
// copies.
assert!(!pkgs.contains(&"app-office/libreoffice"));
assert!(!pkgs.contains(&"www-client/firefox"));
assert!(!pkgs.contains(&"app-text/calibre"));
assert!(!pkgs.contains(&"media-gfx/gimp"));
for (_, id) in FAST_DEFAULT_FLATPAKS {
assert!(
fast_default_flatpak_ids().contains(id),
"missing default Flatpak {id}"
);
}
// Kitty stays; st is never added; pcmanfm is replaced by Nemo.
assert!(pkgs.contains(&"x11-terms/kitty"));
assert!(!pkgs.contains(&"x11-terms/st"));
assert!(!pkgs.contains(&"x11-misc/pcmanfm"));
assert!(pkgs.contains(&"gnome-extra/nemo"));
// Headless stays lean: no desktop applications apply.
assert!(desktop_packages(DesktopProfile::None).is_empty());
assert!(base_packages().contains(&"dev-util/ccache"));
}
#[test]
fn shell_cursor_printing_ssh_power_lanes_are_present() {
let pkgs = desktop_packages(DesktopProfile::Mango);
for atom in [
"app-shells/zsh",
"app-shells/zsh-completions",
"app-shells/zsh-autosuggestions",
"app-shells/zsh-syntax-highlighting",
"x11-themes/vanilla-dmz-xcursors",
"net-print/cups",
"net-misc/openssh",
"sys-power/power-profiles-daemon",
"media-sound/cava",
"gui-apps/matugen",
] {
assert!(pkgs.contains(&atom), "missing lane atom {atom}");
}
assert_eq!(CURSOR_THEME_NAME, "Vanilla-DMZ");
assert_eq!(CURSOR_THEME_SIZE, 24);
assert_eq!(USER_LOGIN_SHELL, "/bin/zsh");
assert_eq!(ROOT_LOGIN_SHELL, "/bin/bash");
assert!(ZSH_SKEL_RC.contains("compinit"));
assert!(ZSH_SKEL_RC.contains("zsh-autosuggestions"));
assert!(ZSH_SKEL_RC.contains("zsh-syntax-highlighting"));
assert!(ZSH_SKEL_RC.contains("up-line-or-beginning-search"));
}
#[test]
fn sshd_is_installed_but_never_enabled_by_default() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Mango;
let svcs = target_services(&cfg);
assert!(svcs.contains(&"cups".to_string()));
assert!(svcs.contains(&"power-profiles-daemon".to_string()));
assert!(
!svcs.iter().any(|s| s == "sshd" || s == "ssh"),
"sshd must stay disabled by default"
);
assert!(SSH_ENABLE_DOC.contains("systemctl enable --now sshd"));
}
#[test]
fn ccache_defaults_cap_at_2g_and_preserve_security() {
assert_eq!(CCACHE_SIZE_DEFAULT, "2G");
let cfg = InstallConfig::default();
let hw = crate::hardware::HardwareReport::default();
let text = make_conf(&cfg, &hw);
assert!(text.contains("FEATURES=\"ccache sandbox usersandbox\""));
assert!(text.contains("CCACHE_SIZE=\"2G\""));
assert!(text.contains("CCACHE_DIR="));
}
#[test]
fn brave_pin_is_fail_closed_and_overlay_is_scoped() {
assert!(validate_brave_pin("").is_err());
assert!(validate_brave_pin("0000000000000000000000000000000000000000").is_err());
assert!(validate_brave_pin("short").is_err());
assert!(validate_brave_pin("gggggggggggggggggggggggggggggggggggggggg").is_err());
assert!(validate_brave_pin("0123456789abcdef0123456789abcdef01234567").is_ok());
let conf = brave_repos_conf("0123456789abcdef0123456789abcdef01234567");
assert!(conf.contains("[another-brave-overlay]"));
assert!(conf.contains(BRAVE_OVERLAY_URI));
assert!(conf.contains("auto-sync = no"));
let mask = brave_scope_mask();
assert!(mask.contains("www-client/brave-browser-beta"));
assert!(mask.contains("www-client/brave-browser-nightly"));
}
#[test]
fn cups_stays_local_only() {
let text = cupsd_local_conf();
assert!(text.contains("Listen localhost:631"));
assert!(text.contains("Browsing Off"));
assert!(text.contains("BrowseLocalProtocols none"));
assert!(text.contains("Allow localhost"));
assert!(!text.contains("Allow all"));
assert!(!text.contains("Port 631\nListen *:631"));
}
#[test]
fn nemo_is_the_default_file_manager() {
let text = nemo_mimeapps();
assert!(text.contains("inode/directory=nemo.desktop"));
}
#[test]
fn fast_defaults_use_bin_atoms_flatpaks_and_one_generic_kernel() {
// No duplicate Portage copies of the Flatpak apps.
let pkgs = workstation_packages();
assert!(pkgs.contains(&"www-client/firefox-bin"));
assert!(pkgs.contains(&"app-office/libreoffice-bin"));
assert!(!pkgs.contains(&"app-text/calibre"));
assert!(!pkgs.contains(&"media-gfx/gimp"));
// Three system-wide Flatpaks, installed in the target only.
assert_eq!(fast_default_flatpak_ids().len(), 3);
assert!(fast_default_flatpak_ids().contains(&"com.calibre_ebook.calibre"));
assert!(fast_default_flatpak_ids().contains(&"org.gimp.GIMP"));
assert!(fast_default_flatpak_ids().contains(&"com.github.tchx84.Flatseal"));
// No broad sandbox override, ever here.
assert!(flatpak_narrow_overrides().is_empty());
// Ordinary-task defaults without touching sandbox protections.
let mime = nemo_mimeapps();
assert!(mime.contains("x-scheme-handler/https=firefox.desktop"));
assert!(mime.contains("application/epub+zip=com.calibre_ebook.calibre.desktop"));
// Installed welcome: once per user, reopenable, never blocking.
assert!(INSTALLED_WELCOME_SCRIPT.contains("--reopen"));
assert!(INSTALLED_WELCOME_SCRIPT.contains("welcome-seen"));
assert!(INSTALLED_WELCOME_AUTOSTART.contains("X-GNOME-Autostart-enabled=true"));
assert!(INSTALLED_WELCOME_DESKTOP_ENTRY.contains("--reopen"));
assert!(INSTALLED_WELCOME_QML.contains("Keep working system and finish"));
assert!(INSTALLED_WELCOME_QML.contains("KeyNavigation.tab"));
let assets = installed_welcome_assets();
assert!(assets.iter().any(|(p, _)| p.contains("shell.qml")));
// DMS first-run suppression seeds the skeleton only.
let seed = dms_firstlaunch_seed("1.6.2");
assert!(seed.iter().any(|(p, _)| p.ends_with(".firstlaunch")));
}
#[test]
fn disk_estimates_require_more_for_the_workstation() {
assert_eq!(
required_disk_gib(DesktopProfile::None),
DISK_MIN_GIB_HEADLESS
);
assert_eq!(required_disk_gib(DesktopProfile::Mango), DISK_MIN_GIB_MANGO);
// The workstation set (~200 packages incl. LibreOffice/Firefox)
// needs substantially more than the lean headless profile.
assert!(required_disk_gib(DesktopProfile::Mango) > required_disk_gib(DesktopProfile::None));
assert!(DISK_RECOMMENDED_GIB_MANGO >= required_disk_gib(DesktopProfile::Mango));
}
#[test]
fn startup_summary_never_claims_all_passed_with_warnings() {
// Zero errors + warnings/optional must not say "All checks passed."
let checks = evaluate_startup_checks(false, true, true, false, false, false);
assert_eq!(checks.len(), 4);
assert!(checks
.iter()
.any(|c| c.id == "blur" && c.severity == CheckSeverity::OptionalUnsupported));
assert!(checks
.iter()
.any(|c| c.id == "power" && c.severity == CheckSeverity::Ok));
assert!(checks
.iter()
.any(|c| c.id == "matugen" && c.severity == CheckSeverity::Warning));
assert!(checks
.iter()
.any(|c| c.id == "cava" && c.severity == CheckSeverity::Warning));
let summary = summarize_checks(&checks);
assert!(!summary.contains("All checks passed"), "{summary}");
assert!(summary.contains("No errors"), "{summary}");
// A conflicting power manager is a required error.
let conflict = evaluate_startup_checks(false, true, true, true, true, true);
let summary = summarize_checks(&conflict);
assert!(summary.contains("error(s)"), "{summary}");
assert!(summary.contains("action required"), "{summary}");
// All green really does pass.
let green = evaluate_startup_checks(true, true, true, false, true, true);
let summary = summarize_checks(&green);
assert!(summary.contains("All 4 checks passed"), "{summary}");
}
}