792 lines
28 KiB
Rust
792 lines
28 KiB
Rust
//! Phoebus OS installer CLI.
|
|
//!
|
|
//! With no mode flags on a terminal, the text UI starts. The deterministic
|
|
//! backend is available directly with `--plan`, `--dry-run` and `--install`.
|
|
//! Secrets are supplied through files, never on the command line.
|
|
|
|
use std::io::Write;
|
|
use std::path::PathBuf;
|
|
use std::process::ExitCode;
|
|
|
|
use clap::Parser;
|
|
use phoebus_ai::provider::ProviderKind;
|
|
use phoebus_core::{InstallConfig, Redactor, SecretString};
|
|
use phoebus_executor::{
|
|
authorize, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner,
|
|
Result,
|
|
};
|
|
use phoebus_installer::Installer;
|
|
use phoebus_tui::TuiOutcome;
|
|
|
|
/// Pinned OpenCode release manifest. Embedded so the static binary needs no
|
|
/// runtime resources. See `resources/opencode.manifest`.
|
|
const OPENCODE_MANIFEST: &str = include_str!("../resources/opencode.manifest");
|
|
|
|
/// Resolve the manifest text. `PHOEBUS_OPENCODE_MANIFEST` overrides the
|
|
/// embedded copy so a fixture can be verified end to end (tests, mirrors).
|
|
fn opencode_manifest() -> std::io::Result<String> {
|
|
match std::env::var("PHOEBUS_OPENCODE_MANIFEST") {
|
|
Ok(path) if !path.is_empty() => std::fs::read_to_string(path),
|
|
_ => Ok(OPENCODE_MANIFEST.to_string()),
|
|
}
|
|
}
|
|
|
|
#[derive(Parser, Debug)]
|
|
#[command(
|
|
name = "phoebus-installer",
|
|
version,
|
|
about = "Phoebus OS installer (deterministic backend + TUI)"
|
|
)]
|
|
struct Cli {
|
|
/// Load configuration from a file (TOML or the legacy flat format).
|
|
#[arg(long)]
|
|
config: Option<PathBuf>,
|
|
|
|
/// Render the installation plan and exit.
|
|
#[arg(long)]
|
|
plan: bool,
|
|
|
|
/// Do not execute commands or modify the target.
|
|
#[arg(long)]
|
|
dry_run: bool,
|
|
|
|
/// Run the deterministic backend without the TUI.
|
|
#[arg(long)]
|
|
install: bool,
|
|
|
|
/// Skip interactive confirmations (for unattended installs).
|
|
#[arg(long, short = 'y')]
|
|
yes: bool,
|
|
|
|
/// Read the LUKS passphrase from a 0600 file.
|
|
#[arg(long)]
|
|
luks_passphrase_file: Option<PathBuf>,
|
|
|
|
/// Read the user password from a 0600 file.
|
|
#[arg(long)]
|
|
user_password_file: Option<PathBuf>,
|
|
|
|
/// Read the root password from a 0600 file.
|
|
#[arg(long)]
|
|
root_password_file: Option<PathBuf>,
|
|
|
|
/// Write the effective configuration as TOML and exit.
|
|
#[arg(long)]
|
|
save_config: Option<PathBuf>,
|
|
|
|
/// Fetch and verify the pinned OpenCode release, then exit.
|
|
#[arg(long)]
|
|
bootstrap_opencode: bool,
|
|
|
|
/// Enable AI-assisted optimization (opt-in). The facts sent are shown first.
|
|
#[arg(long)]
|
|
ai: bool,
|
|
|
|
/// AI provider: `deepseek`, `openai`/`chatgpt`, or `none`.
|
|
#[arg(long, value_name = "PROVIDER")]
|
|
ai_provider: Option<String>,
|
|
|
|
/// Model name override for the selected provider.
|
|
#[arg(long, value_name = "MODEL")]
|
|
ai_model: Option<String>,
|
|
|
|
/// Read the provider API key from a mode-0600 file (never stored in config).
|
|
#[arg(long, value_name = "FILE")]
|
|
ai_api_key_file: Option<PathBuf>,
|
|
|
|
/// Apply a proposal from a file (a chat response or a bare proposal JSON).
|
|
#[arg(long, value_name = "FILE")]
|
|
ai_proposal_file: Option<PathBuf>,
|
|
|
|
/// Print the system facts that would be sent to the model, then exit.
|
|
#[arg(long)]
|
|
ai_facts: bool,
|
|
|
|
/// Override the provider endpoint (self-hosted/local models).
|
|
#[arg(long, value_name = "URL")]
|
|
ai_endpoint: Option<String>,
|
|
|
|
/// Install without AI (break-glass for recovery/automation). Also
|
|
/// `--legacy` or `PHOEBUS_NO_AI=1`.
|
|
#[arg(long, alias = "legacy")]
|
|
no_ai: bool,
|
|
|
|
/// Print a named desktop asset (session scripts, config, entries) and exit.
|
|
/// Used by the live ISO build so it reuses the installer's exact assets.
|
|
#[arg(long, value_name = "NAME", hide = true)]
|
|
emit_asset: Option<String>,
|
|
|
|
/// Verify that an assembled live rootfs bundles a complete NVIDIA payload
|
|
/// (kernel modules for its kernel, userspace, Wayland/EGL/GBM integration
|
|
/// and firmware), write the version record to /etc/phoebus/nvidia, and exit.
|
|
/// Fails (nonzero) on any missing or mismatched component. Used by the live
|
|
/// ISO build, including cached-rootfs builds.
|
|
#[arg(long, value_name = "ROOTFS", hide = true)]
|
|
verify_live_nvidia: Option<PathBuf>,
|
|
|
|
/// The NVIDIA driver version bundled in the live image (recorded by
|
|
/// `--verify-live-nvidia`).
|
|
#[arg(long, value_name = "VERSION", hide = true)]
|
|
nvidia_version: Option<String>,
|
|
|
|
/// The NVIDIA kernel-module flavor bundled in the live image:
|
|
/// `proprietary` (default) or `open`.
|
|
#[arg(long, value_name = "FLAVOR", hide = true)]
|
|
nvidia_flavor: Option<String>,
|
|
|
|
/// Print the live medium's display-driver decision as stable `key=value`
|
|
/// lines and exit. Consumed by the live-only `phoebus-nvidia-load`
|
|
/// service; the decision comes from the actual PCI display devices and the
|
|
/// bundled branch's capabilities, never from a vendor-name match.
|
|
#[arg(long, hide = true)]
|
|
live_gpu_plan: bool,
|
|
|
|
/// Override the sysfs root used by `--live-gpu-plan` (fixtures/testing).
|
|
#[arg(long, value_name = "PATH", hide = true)]
|
|
sysfs_root: Option<PathBuf>,
|
|
|
|
/// Override the kernel command line used by `--live-gpu-plan`.
|
|
#[arg(long, value_name = "CMDLINE", hide = true)]
|
|
kernel_cmdline: Option<String>,
|
|
|
|
/// Speak the typed JSON protocol used by the graphical installer frontend
|
|
/// (stdin/stdout). Not intended for direct interactive use.
|
|
#[arg(long, hide = true)]
|
|
gui_bridge: bool,
|
|
|
|
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
|
|
/// its capability as JSON. Read-only; exits nonzero unless a model catalog
|
|
/// is available. Never prints provider credentials.
|
|
#[arg(long, value_name = "URL")]
|
|
opencode_probe: Option<String>,
|
|
|
|
/// Obtain a real model response through an OpenCode server and validate it,
|
|
/// then exit. This is the acceptance test for inference, not reachability.
|
|
#[arg(long, value_name = "URL")]
|
|
opencode_test: Option<String>,
|
|
|
|
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
|
|
#[arg(long, value_name = "URL")]
|
|
opencode_server: Option<String>,
|
|
|
|
/// OpenCode provider id (e.g. `deepseek`).
|
|
#[arg(long, value_name = "PROVIDER")]
|
|
opencode_provider: Option<String>,
|
|
|
|
/// OpenCode model id (e.g. `deepseek-chat`).
|
|
#[arg(long, value_name = "MODEL")]
|
|
opencode_model: Option<String>,
|
|
|
|
/// Read the OpenCode server password from a mode-0600 file (distinct from a
|
|
/// model provider API key).
|
|
#[arg(long, value_name = "FILE")]
|
|
opencode_password_file: Option<PathBuf>,
|
|
|
|
/// AI backend for install guidance: `direct` (default) or `opencode`.
|
|
#[arg(long, value_name = "BACKEND")]
|
|
ai_backend: Option<String>,
|
|
}
|
|
|
|
/// Verify the live rootfs's bundled NVIDIA payload and write its record. This
|
|
/// is a build-time gate: a missing module, library or firmware file makes the
|
|
/// live ISO build fail rather than shipping an image that cannot accelerate the
|
|
/// GPU it advertises. It is independent of any cached-rootfs path.
|
|
fn verify_live_nvidia_command(cli: &Cli, rootfs: &std::path::Path) -> ExitCode {
|
|
use phoebus_core::NvidiaModuleFlavor;
|
|
let version = cli.nvidia_version.clone().unwrap_or_default();
|
|
if version.trim().is_empty() {
|
|
eprintln!("--verify-live-nvidia requires --nvidia-version");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
let flavor = match cli.nvidia_flavor.as_deref().unwrap_or("proprietary") {
|
|
"open" => NvidiaModuleFlavor::Open,
|
|
"proprietary" => NvidiaModuleFlavor::Proprietary,
|
|
other => {
|
|
eprintln!("unknown --nvidia-flavor `{other}` (expected `proprietary` or `open`)");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
match phoebus_executor::live_nvidia::verify_live_nvidia(rootfs, &version, flavor) {
|
|
Ok(payload) => {
|
|
let dir = rootfs.join("etc/phoebus");
|
|
if let Err(e) = std::fs::create_dir_all(&dir) {
|
|
eprintln!("cannot create {}: {e}", dir.display());
|
|
return ExitCode::FAILURE;
|
|
}
|
|
if let Err(e) = std::fs::write(dir.join("nvidia"), payload.record()) {
|
|
eprintln!("cannot write the NVIDIA record: {e}");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
println!("{}", payload.render());
|
|
ExitCode::SUCCESS
|
|
}
|
|
Err(e) => {
|
|
eprintln!("NVIDIA live payload verification failed: {e}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Print the live medium's display-driver decision as stable `key=value` lines.
|
|
///
|
|
/// This is the single authority the live-only `phoebus-nvidia-load` service
|
|
/// consults. It is deterministic, read-only and outside the AI boundary: the
|
|
/// action follows the actual PCI display devices and the bundled branch, and
|
|
/// fail-safe graphics (`nomodeset` / `phoebus.nvidia=off`) always wins.
|
|
fn live_gpu_plan_command(cli: &Cli) -> ExitCode {
|
|
let sysfs = cli
|
|
.sysfs_root
|
|
.clone()
|
|
.unwrap_or_else(|| PathBuf::from("/sys"));
|
|
let cmdline = cli
|
|
.kernel_cmdline
|
|
.clone()
|
|
.or_else(|| std::fs::read_to_string("/proc/cmdline").ok())
|
|
.unwrap_or_default();
|
|
let fail_safe = cmdline
|
|
.split_whitespace()
|
|
.any(|tok| tok == "nomodeset" || tok == "phoebus.nvidia=off");
|
|
let gpus = phoebus_executor::probe::probe_nvidia_display_devices(&sysfs);
|
|
let devices: Vec<phoebus_core::nvidia::NvidiaDevice> = gpus
|
|
.iter()
|
|
.map(phoebus_core::nvidia::NvidiaDevice::from_gpu)
|
|
.collect();
|
|
let plan = phoebus_core::nvidia::live_nvidia_plan(&devices, fail_safe);
|
|
print!("{}", plan.render());
|
|
ExitCode::SUCCESS
|
|
}
|
|
|
|
struct TerminalConfirm;
|
|
|
|
impl Confirmation for TerminalConfirm {
|
|
fn confirm_erase(&self, preview: &str) -> Result<bool> {
|
|
println!("\n{preview}");
|
|
print!("\nType ERASE to continue: ");
|
|
std::io::stdout().flush().ok();
|
|
let mut line = String::new();
|
|
std::io::stdin().read_line(&mut line).map_err(|e| {
|
|
phoebus_executor::ExecError::operation("confirm", "erase", e.to_string())
|
|
})?;
|
|
Ok(line.trim() == "ERASE")
|
|
}
|
|
|
|
fn confirm_final(&self, message: &str) -> Result<bool> {
|
|
print!("{message} [y/N] ");
|
|
std::io::stdout().flush().ok();
|
|
let mut line = String::new();
|
|
std::io::stdin().read_line(&mut line).map_err(|e| {
|
|
phoebus_executor::ExecError::operation("confirm", "final", e.to_string())
|
|
})?;
|
|
Ok(matches!(
|
|
line.trim().to_ascii_lowercase().as_str(),
|
|
"y" | "yes"
|
|
))
|
|
}
|
|
}
|
|
|
|
fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
|
|
let value = std::fs::read_to_string(path)?;
|
|
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
|
|
}
|
|
|
|
/// A lightweight `Exec` for the OpenCode probe/test commands, which do not
|
|
/// touch the target.
|
|
fn opencode_exec() -> Exec {
|
|
let dir = std::env::temp_dir().join("phoebus-opencode-cli");
|
|
let _ = std::fs::create_dir_all(&dir);
|
|
let logger = Logger::open(dir.join("opencode.log"), Redactor::new(), false);
|
|
Exec::new(Box::new(RealRunner::new()), logger, false, dir.clone(), dir)
|
|
}
|
|
|
|
/// Probe an OpenCode server (`validate_inference = false`) or obtain and
|
|
/// validate a real model response (`true`). Exits nonzero unless the requested
|
|
/// condition is met, so it can be used as an acceptance command.
|
|
fn run_opencode_probe(cli: &Cli, url: &str, validate_inference: bool) -> ExitCode {
|
|
use phoebus_executor::opencode_client::{CurlHttpClient, OpenCodeClient};
|
|
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint, ProbeRequest};
|
|
|
|
let endpoint = match Endpoint::parse(url) {
|
|
Ok(endpoint) => endpoint,
|
|
Err(e) => {
|
|
eprintln!("invalid OpenCode endpoint `{url}`: {e}");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
let auth = match &cli.opencode_password_file {
|
|
Some(path) => match read_secret(path) {
|
|
Ok(secret) => Some(secret),
|
|
Err(e) => {
|
|
eprintln!("cannot read OpenCode password file: {e}");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
},
|
|
None => None,
|
|
};
|
|
let provider = cli.opencode_provider.clone().unwrap_or_default();
|
|
let model = cli.opencode_model.clone().unwrap_or_default();
|
|
let exec = opencode_exec();
|
|
let http = CurlHttpClient::new(&exec);
|
|
|
|
if !validate_inference {
|
|
let mut request = ProbeRequest::new();
|
|
request.auth = auth.clone();
|
|
request.provider = (!provider.is_empty()).then(|| provider.clone());
|
|
request.model = (!model.is_empty()).then(|| model.clone());
|
|
let capability = probe(&http, &endpoint, &request);
|
|
match serde_json::to_string_pretty(&capability) {
|
|
Ok(json) => println!("{json}"),
|
|
Err(e) => eprintln!("could not render capability: {e}"),
|
|
}
|
|
return if matches!(
|
|
capability.state,
|
|
ConnectionState::ModelCatalog | ConnectionState::Ready
|
|
) {
|
|
ExitCode::SUCCESS
|
|
} else {
|
|
ExitCode::FAILURE
|
|
};
|
|
}
|
|
|
|
if provider.is_empty() || model.is_empty() {
|
|
eprintln!("--opencode-test requires --opencode-provider and --opencode-model");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model).with_auth(auth);
|
|
match client.one_shot(
|
|
"You are a connectivity test. Reply with JSON only.",
|
|
"Reply with exactly {\"phoebus\":\"ok\"} and nothing else.",
|
|
) {
|
|
Ok(reply) => match serde_json::from_str::<serde_json::Value>(&reply.content) {
|
|
Ok(value) if value.get("phoebus").and_then(|v| v.as_str()) == Some("ok") => {
|
|
println!("validated model response: {}", reply.content);
|
|
ExitCode::SUCCESS
|
|
}
|
|
Ok(value) => {
|
|
println!("model responded, but not as requested: {value}");
|
|
ExitCode::FAILURE
|
|
}
|
|
Err(_) => {
|
|
println!("model response was not JSON: {}", reply.content);
|
|
ExitCode::FAILURE
|
|
}
|
|
},
|
|
Err(e) => {
|
|
eprintln!("model validation failed: {e}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The provider selected on the command line, or the one the TUI/config chose.
|
|
fn resolve_provider(
|
|
cli: &Cli,
|
|
config: &InstallConfig,
|
|
) -> std::result::Result<ProviderKind, Box<dyn std::error::Error>> {
|
|
let raw = cli
|
|
.ai_provider
|
|
.as_deref()
|
|
.unwrap_or(config.ai.provider.as_str());
|
|
ProviderKind::parse(raw).ok_or_else(|| {
|
|
format!("unknown AI provider `{raw}` (use deepseek, openai, local or none)").into()
|
|
})
|
|
}
|
|
|
|
/// Whether the user explicitly asked for a deterministic, no-AI run.
|
|
fn no_ai_requested(cli: &Cli) -> bool {
|
|
cli.no_ai
|
|
|| std::env::var("PHOEBUS_NO_AI")
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Installing Phoebus requires a **validated** AI interaction, not just a
|
|
/// non-empty provider name. `--no-ai`/`--legacy` is the explicit, documented
|
|
/// break-glass for recovery or automation.
|
|
fn require_ai_for_install(
|
|
cli: &Cli,
|
|
validated: bool,
|
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
if no_ai_requested(cli) || validated {
|
|
return Ok(());
|
|
}
|
|
Err(
|
|
"installing Phoebus requires a successful, validated AI interaction.\n\
|
|
Connect a provider (--ai-backend direct with --ai-provider \
|
|
deepseek|openai|local and --ai-api-key-file/--ai-endpoint, or \
|
|
--ai-backend opencode with --opencode-server/--opencode-provider/\
|
|
--opencode-model) and let it return a valid proposal, or pass --no-ai \
|
|
(alias --legacy) for a deterministic install."
|
|
.into(),
|
|
)
|
|
}
|
|
|
|
/// Apply AI guidance to the configuration before the plan is shown or install
|
|
/// runs. Returns `true` only when a model interaction produced a valid,
|
|
/// reviewed proposal. The model never sees secrets and never executes anything.
|
|
fn run_ai_guidance(
|
|
cli: &Cli,
|
|
installer: &mut Installer,
|
|
) -> std::result::Result<bool, Box<dyn std::error::Error>> {
|
|
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
|
|
if !wants_ai {
|
|
return Ok(false);
|
|
}
|
|
|
|
if let Some(path) = &cli.ai_proposal_file {
|
|
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
|
|
println!("{}", outcome.render());
|
|
return Ok(true);
|
|
}
|
|
|
|
let backend = cli
|
|
.ai_backend
|
|
.as_deref()
|
|
.and_then(phoebus_core::AiBackend::parse)
|
|
.unwrap_or(installer.config.ai.backend);
|
|
let facts = installer.system_facts();
|
|
|
|
if backend == phoebus_core::AiBackend::OpenCode {
|
|
let server = cli
|
|
.opencode_server
|
|
.clone()
|
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
|
|
.unwrap_or_else(|| installer.config.ai.opencode_server.clone());
|
|
let provider_id = cli
|
|
.opencode_provider
|
|
.clone()
|
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
|
|
.unwrap_or_else(|| installer.config.ai.opencode_provider.clone());
|
|
let model = cli
|
|
.opencode_model
|
|
.clone()
|
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
|
|
.unwrap_or_else(|| installer.config.ai.opencode_model.clone());
|
|
if server.trim().is_empty() || provider_id.trim().is_empty() || model.trim().is_empty() {
|
|
eprintln!(
|
|
"AI assistance is enabled but OpenCode is not fully configured \
|
|
(need server, provider and model); continuing without AI."
|
|
);
|
|
return Ok(false);
|
|
}
|
|
let password = match &cli.opencode_password_file {
|
|
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
|
|
None => None,
|
|
};
|
|
eprintln!(
|
|
"Sending these system facts through the OpenCode server at {} \
|
|
(provider {}, no passwords, passphrases or files):",
|
|
server, provider_id
|
|
);
|
|
eprintln!("{}", facts.render());
|
|
let transport = phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
|
&installer.exec,
|
|
server.clone(),
|
|
provider_id.clone(),
|
|
model.clone(),
|
|
)
|
|
.with_auth(password);
|
|
return match phoebus_installer::ai_guide::generate_and_review_at(
|
|
&mut installer.config,
|
|
&facts,
|
|
ProviderKind::Local,
|
|
&server,
|
|
&model,
|
|
&transport,
|
|
) {
|
|
Ok(outcome) => {
|
|
println!("{}", outcome.render());
|
|
Ok(true)
|
|
}
|
|
Err(e) => {
|
|
eprintln!("OpenCode proposal rejected; continuing with the proven defaults: {e}");
|
|
Ok(false)
|
|
}
|
|
};
|
|
}
|
|
|
|
let provider = resolve_provider(cli, &installer.config)?;
|
|
if provider == ProviderKind::None {
|
|
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
|
|
return Ok(false);
|
|
}
|
|
eprintln!(
|
|
"Sending these system facts to {} (no passwords, passphrases or files):",
|
|
provider.as_str()
|
|
);
|
|
eprintln!("{}", facts.render());
|
|
|
|
let endpoint = cli
|
|
.ai_endpoint
|
|
.clone()
|
|
.unwrap_or_else(|| provider.endpoint().to_string());
|
|
let api_key = match (&cli.ai_api_key_file, provider.requires_key()) {
|
|
(Some(path), _) => Some(phoebus_executor::ai::load_api_key(path)?),
|
|
(None, true) => {
|
|
return Err(format!(
|
|
"--ai-api-key-file is required for provider `{}`",
|
|
provider.as_str()
|
|
)
|
|
.into());
|
|
}
|
|
(None, false) => None,
|
|
};
|
|
let model = cli.ai_model.clone().unwrap_or_default();
|
|
let transport = phoebus_executor::ai::CurlTransport::new(&installer.exec, api_key);
|
|
match phoebus_installer::ai_guide::generate_and_review_at(
|
|
&mut installer.config,
|
|
&facts,
|
|
provider,
|
|
&endpoint,
|
|
&model,
|
|
&transport,
|
|
) {
|
|
Ok(outcome) => {
|
|
println!("{}", outcome.render());
|
|
Ok(true)
|
|
}
|
|
Err(e) => {
|
|
eprintln!("AI proposal rejected; continuing with the proven defaults: {e}");
|
|
Ok(false)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() -> ExitCode {
|
|
match run() {
|
|
Ok(code) => code,
|
|
Err(e) => {
|
|
eprintln!("error: {e}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
|
|
let cli = Cli::parse();
|
|
|
|
if cli.gui_bridge {
|
|
phoebus_installer::gui_bridge::run_stdio()?;
|
|
return Ok(ExitCode::SUCCESS);
|
|
}
|
|
|
|
if let Some(url) = &cli.opencode_probe {
|
|
return Ok(run_opencode_probe(&cli, url, false));
|
|
}
|
|
if let Some(url) = &cli.opencode_test {
|
|
return Ok(run_opencode_probe(&cli, url, true));
|
|
}
|
|
|
|
if let Some(name) = &cli.emit_asset {
|
|
return match phoebus_core::system::desktop_asset(name) {
|
|
Some(text) => {
|
|
print!("{text}");
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
None => {
|
|
eprintln!("unknown desktop asset: {name}");
|
|
Ok(ExitCode::FAILURE)
|
|
}
|
|
};
|
|
}
|
|
|
|
if cli.live_gpu_plan {
|
|
return Ok(live_gpu_plan_command(&cli));
|
|
}
|
|
|
|
if let Some(rootfs) = &cli.verify_live_nvidia {
|
|
return Ok(verify_live_nvidia_command(&cli, rootfs));
|
|
}
|
|
|
|
let mut config = if let Some(path) = &cli.config {
|
|
InstallConfig::load_from_path(path)?
|
|
} else {
|
|
InstallConfig::default()
|
|
};
|
|
if cli.dry_run {
|
|
config.runtime.dry_run = true;
|
|
}
|
|
if cli.yes {
|
|
config.runtime.assume_yes = true;
|
|
}
|
|
|
|
// Secrets may come from CLI files or the TUI.
|
|
let mut luks = cli
|
|
.luks_passphrase_file
|
|
.as_ref()
|
|
.map(read_secret)
|
|
.transpose()?;
|
|
let mut user_pw = cli
|
|
.user_password_file
|
|
.as_ref()
|
|
.map(read_secret)
|
|
.transpose()?;
|
|
let root_pw = cli
|
|
.root_password_file
|
|
.as_ref()
|
|
.map(read_secret)
|
|
.transpose()?;
|
|
let mut tui_confirmed = false;
|
|
let mut do_install = cli.install;
|
|
|
|
// TUI when no explicit mode and a terminal is present.
|
|
if !cli.plan && !cli.install && !cli.dry_run && !cli.bootstrap_opencode && phoebus_tui::is_tty()
|
|
{
|
|
match phoebus_tui::run(config.clone())? {
|
|
TuiOutcome::Exit => return Ok(ExitCode::SUCCESS),
|
|
TuiOutcome::Save(saved) => {
|
|
let path = cli
|
|
.config
|
|
.clone()
|
|
.unwrap_or_else(|| PathBuf::from("phoebus-install.toml"));
|
|
std::fs::write(&path, saved.to_toml_string()?)?;
|
|
println!("wrote {}", path.display());
|
|
return Ok(ExitCode::SUCCESS);
|
|
}
|
|
TuiOutcome::Install(saved, tui_luks, tui_user) => {
|
|
config = saved;
|
|
if luks.is_none() {
|
|
luks = tui_luks;
|
|
}
|
|
if user_pw.is_none() {
|
|
user_pw = tui_user;
|
|
}
|
|
do_install = true;
|
|
tui_confirmed = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut state_dir = PathBuf::from(&config.runtime.state_dir);
|
|
if std::fs::create_dir_all(&state_dir).is_err() {
|
|
state_dir = PathBuf::from("/tmp/phoebus-installer");
|
|
std::fs::create_dir_all(&state_dir).ok();
|
|
}
|
|
let log_path = state_dir.join("install.log");
|
|
|
|
let echo = std::env::var("PHOEBUS_LOG_ECHO")
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "yes" | "1" | "true"))
|
|
.unwrap_or(false);
|
|
let logger = Logger::open(&log_path, Redactor::new(), echo);
|
|
|
|
let root = if config.runtime.dry_run {
|
|
let sandbox = state_dir.join("dry-run-root");
|
|
std::fs::create_dir_all(&sandbox).ok();
|
|
sandbox
|
|
} else {
|
|
PathBuf::from(&config.storage.install_root)
|
|
};
|
|
|
|
let logger_clone = logger.clone();
|
|
let runner = RealRunner::with_sink(std::sync::Arc::new(move |text: &str| {
|
|
logger_clone.stream_output(text);
|
|
}));
|
|
let exec = Exec::new(
|
|
Box::new(runner),
|
|
logger,
|
|
config.runtime.dry_run,
|
|
root,
|
|
state_dir.clone(),
|
|
);
|
|
for secret in [&luks, &user_pw, &root_pw].into_iter().flatten() {
|
|
exec.register_secret(secret);
|
|
}
|
|
|
|
if cli.bootstrap_opencode {
|
|
let manifest = phoebus_executor::opencode::Manifest::parse(&opencode_manifest()?);
|
|
let dest = phoebus_executor::opencode::bin_dir(&state_dir);
|
|
let installed = phoebus_executor::opencode::ensure(&exec, &manifest, &dest)?;
|
|
println!("OpenCode ready at {}", installed.display());
|
|
return Ok(ExitCode::SUCCESS);
|
|
}
|
|
|
|
let mut installer = Installer::new(config, exec);
|
|
|
|
if cli.ai_facts {
|
|
println!("{}", installer.system_facts().render());
|
|
return Ok(ExitCode::SUCCESS);
|
|
}
|
|
let ai_validated = run_ai_guidance(&cli, &mut installer)?;
|
|
// CLI parity with the GUI bridge: hold the validated credential in memory
|
|
// so finalize can persist it when reuse is selected (default).
|
|
if installer.config.ai.reuse_ai_connection {
|
|
let api_key = match &cli.ai_api_key_file {
|
|
Some(p) => phoebus_executor::ai::load_api_key(p).ok(),
|
|
None => None,
|
|
};
|
|
let opencode_pw = match &cli.opencode_password_file {
|
|
Some(p) => phoebus_executor::ai::load_api_key(p).ok(),
|
|
None => None,
|
|
};
|
|
if api_key.is_some() || opencode_pw.is_some() {
|
|
installer.set_pending_ai_credentials(api_key, opencode_pw);
|
|
}
|
|
}
|
|
|
|
// AI is mandatory to install, and a validated interaction (not merely a
|
|
// provider name) is required; a deterministic no-AI run needs the explicit
|
|
// break-glass. Dry-run and plan modes are exempt.
|
|
if do_install && !installer.config.runtime.dry_run {
|
|
require_ai_for_install(&cli, ai_validated)?;
|
|
}
|
|
|
|
if let Some(path) = &cli.save_config {
|
|
std::fs::write(path, installer.config.to_toml_string()?)?;
|
|
println!("wrote {}", path.display());
|
|
}
|
|
|
|
// Plan / default mode.
|
|
if cli.plan || !do_install {
|
|
print!("{}", installer.render_plan());
|
|
let issues = installer.validate();
|
|
println!("\nValidation:");
|
|
if issues.is_empty() {
|
|
println!(" OK");
|
|
} else {
|
|
for issue in &issues {
|
|
println!(" - {issue}");
|
|
}
|
|
}
|
|
return Ok(ExitCode::SUCCESS);
|
|
}
|
|
|
|
// Install mode.
|
|
let issues = installer.validate();
|
|
if !issues.is_empty() {
|
|
eprintln!("configuration is incomplete:");
|
|
for issue in &issues {
|
|
eprintln!(" - {issue}");
|
|
}
|
|
return Ok(ExitCode::FAILURE);
|
|
}
|
|
|
|
print!("{}", installer.render_plan());
|
|
|
|
let auth: DestructiveAuthorization = if tui_confirmed || installer.config.runtime.assume_yes {
|
|
authorize(
|
|
&AutoConfirm,
|
|
&installer.destructive_preview(),
|
|
"Start installation?",
|
|
)?
|
|
} else {
|
|
let preview = installer.destructive_preview();
|
|
authorize(
|
|
&TerminalConfirm,
|
|
&preview,
|
|
"Start the installation now? This can take a long time.",
|
|
)?
|
|
};
|
|
|
|
installer.install(&auth, luks.as_ref(), user_pw.as_ref(), root_pw.as_ref())?;
|
|
if installer.config.runtime.dry_run {
|
|
println!(
|
|
"dry-run complete; log: {}",
|
|
installer.exec.log_path().display()
|
|
);
|
|
} else {
|
|
println!(
|
|
"installation complete; log: {}",
|
|
installer.exec.log_path().display()
|
|
);
|
|
}
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|