//! First-run setup, run by `kur setup` and by a bare `kur` when the config file is missing. //! Each step is idempotent, so running it again repairs or reinstalls whatever is missing. use crate::Res; use crate::config; use crate::install::{file_sha256, systemctl}; use std::env; use std::fs::{self, DirBuilder, File, OpenOptions, Permissions}; use std::io::{self, Write}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; use std::path::Path; /// Starter config. Must parse with `config::load`; the commented-out entry must stay fully commented. const CONFIG_TEMPLATE: &str = r##"# kur config, written by `kur setup`. Field reference: README.md. # Paths may start with ~/, which expands to $HOME/. This file is mode 0600: keep it that way. # Forge base URL. A trailing slash is fine. forge = "https://git.tahinli.com" # Optional: file holding a forge token for private repos. Read once at start, trimmed. # Use a read-only token. Must be mode 0600. # token_file = "~/.config/kur/token" # kur updates itself. There is no unit: the new binary is swapped in and used from the next # timer run on. kur runs `kur --version` on the new build before swapping it in, so a broken # build is never installed. [[app]] name = "kur" repo = "Tahinli/kur" asset = "kur-{arch}-linux" path = "~/bin/kur" check = ["--version"] # Uncomment once im runs as a user unit of this account and has a v* release. # [[app]] # name = "im" # repo = "Tahinli/im" # asset = "im-{arch}-linux" # path = "~/bin/im" # unit = "im.service" # health_url = "http://127.0.0.1:7650/healthz" "##; const KUR_SERVICE: &str = include_str!("../deploy/user/kur.service"); const KUR_TIMER: &str = include_str!("../deploy/user/kur.timer"); const ROOT_MSG: &str = "run kur as the account that runs the apps, not as root"; const SYSTEMCTL_MSG: &str = "systemctl --user failed; kur needs a login session of this account (for example: sudo machinectl shell @)"; /// Runs every setup step in order and stops at the first error. pub fn run(config_path: &Path) -> Res<()> { refuse_root()?; let home = config::home_dir().ok_or("HOME is not set")?; install_binary(&home)?; write_config(config_path)?; write_units(&config::config_base()?.join("systemd").join("user"))?; enable_timer()?; println!("kur: setup: config file {}", config_path.display()); println!("kur: setup: done; kur checks for updates every 5 minutes (journalctl --user -u kur)"); Ok(()) } /// Step 1: refuses to run as root. fn refuse_root() -> Res<()> { let uid = fs::metadata("/proc/self") .map_err(|e| format!("cannot read /proc/self: {e}"))? .uid(); if uid == 0 { return Err(ROOT_MSG.into()); } Ok(()) } /// Step 2: copies the running binary to `$HOME/bin/kur` unless the target already matches. fn install_binary(home: &Path) -> Res<()> { let source = env::current_exe().map_err(|e| format!("cannot find the running kur binary: {e}"))?; let bin_dir = home.join("bin"); let target = bin_dir.join("kur"); let display = target.display(); let same_file = matches!( (fs::canonicalize(&source), fs::canonicalize(&target)), (Ok(a), Ok(b)) if a == b ); if same_file { println!("kur: setup: binary already in place ({display})"); return Ok(()); } let source_sha = file_sha256(&source)?.ok_or("cannot read the running kur binary")?; if file_sha256(&target)?.as_deref() == Some(source_sha.as_str()) { println!("kur: setup: binary already in place ({display})"); return Ok(()); } if !bin_dir.is_dir() { DirBuilder::new() .mode(0o755) .create(&bin_dir) .and_then(|()| fs::set_permissions(&bin_dir, Permissions::from_mode(0o755))) .map_err(|e| format!("create {}: {e}", bin_dir.display()))?; } let bytes = fs::read(&source).map_err(|e| format!("read {}: {e}", source.display()))?; write_atomic(&target, &bytes, 0o755).map_err(|e| format!("install {display}: {e}"))?; println!("kur: setup: installed binary to {display}"); Ok(()) } /// Step 3: writes the starter config if the file does not exist. An existing file is never touched. fn write_config(path: &Path) -> Res<()> { let display = path.display(); if path .try_exists() .map_err(|e| format!("cannot check {display}: {e}"))? { println!("kur: setup: config already in place ({display})"); return Ok(()); } if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) { DirBuilder::new() .recursive(true) .mode(0o700) .create(dir) .map_err(|e| format!("create {}: {e}", dir.display()))?; } // Mode 0600 from creation, so the file is never readable by others. let result = OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path) .and_then(|mut file| { file.write_all(CONFIG_TEMPLATE.as_bytes())?; file.sync_all() }); result.map_err(|e| format!("write config {display}: {e}"))?; println!("kur: setup: wrote starter config {display}"); Ok(()) } /// Step 4: writes the embedded user units into `dir`, only where missing or different. fn write_units(dir: &Path) -> Res<()> { DirBuilder::new() .recursive(true) .mode(0o755) .create(dir) .map_err(|e| format!("create {}: {e}", dir.display()))?; let mut changed = false; for (name, content) in [("kur.service", KUR_SERVICE), ("kur.timer", KUR_TIMER)] { let path = dir.join(name); if fs::read_to_string(&path).ok().as_deref() == Some(content) { continue; } write_atomic(&path, content.as_bytes(), 0o644) .map_err(|e| format!("write {}: {e}", path.display()))?; changed = true; } if changed { println!("kur: setup: wrote user units to {}", dir.display()); } else { println!( "kur: setup: user units already in place ({})", dir.display() ); } Ok(()) } /// Step 5: reloads the user manager and enables the timer. Needs a login session of this account. fn enable_timer() -> Res<()> { // Without XDG_RUNTIME_DIR there is no user manager to talk to, so fail before calling systemctl. if env::var_os("XDG_RUNTIME_DIR").is_none_or(|value| value.is_empty()) { return Err(SYSTEMCTL_MSG.into()); } systemctl(&["daemon-reload"]).map_err(|_| SYSTEMCTL_MSG.to_string())?; systemctl(&["enable", "--now", "kur.timer"]).map_err(|_| SYSTEMCTL_MSG.to_string())?; println!("kur: setup: kur.timer enabled and started"); Ok(()) } /// Writes `bytes` to a temp file next to `path` with `mode`, fsyncs it, then renames it over `path`. fn write_atomic(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { let mut name = path.file_name().unwrap_or_default().to_os_string(); name.push(".kur-new"); let tmp = path.with_file_name(name); let _ = fs::remove_file(&tmp); let result = write_tmp_and_rename(&tmp, path, bytes, mode); if result.is_err() { let _ = fs::remove_file(&tmp); } result } fn write_tmp_and_rename(tmp: &Path, path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { let mut file = OpenOptions::new() .write(true) .create_new(true) .mode(mode) .open(tmp)?; file.write_all(bytes)?; file.set_permissions(Permissions::from_mode(mode))?; file.sync_all()?; drop(file); fs::rename(tmp, path)?; let parent = match path.parent() { Some(dir) if !dir.as_os_str().is_empty() => dir, _ => Path::new("."), }; File::open(parent)?.sync_all() }