use std::{env, ffi::OsStr, fs, io, path::Path, process::ExitCode};
const ABOUT: &str = "aevOS by Knott Dynamics\nA Linux desktop built around Aen and KnottCompositor. The Blackout USB preview includes Lios, workspace tiling, and a guided Scrin installer.";
const USAGE: &str = "Usage: aev-os [about | identify [OS-RELEASE] | --version]";
fn distribution_id(release: &str) -> Option<&str> {
let value = release
.lines()
.rev()
.find_map(|line| line.trim().strip_prefix("ID="))?;
let id = value
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
.unwrap_or(value);
(!id.is_empty()
&& id
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)))
.then_some(id)
}
fn identify(path: Option<&OsStr>) -> Result<bool, String> {
let mut source = path.map(Path::new).unwrap_or(Path::new("/etc/os-release"));
let mut data = fs::read_to_string(source);
if path.is_none() && matches!(&data, Err(e) if e.kind() == io::ErrorKind::NotFound) {
source = Path::new("/usr/lib/os-release");
data = fs::read_to_string(source);
}
let text = data.map_err(|e| format!("{}: {e}", source.display()))?;
let id = distribution_id(&text)
.ok_or_else(|| format!("{} has no valid distribution ID", source.display()))?;
if id == "knottos" {
println!("aevOS (distribution ID: {id})");
Ok(true)
} else {
println!("Other distribution (ID: {id})");
Ok(false)
}
}
fn main() -> ExitCode {
let args: Vec<_> = env::args_os().skip(1).collect();
match args.as_slice() {
[] => println!("{ABOUT}"),
[cmd] if cmd == "about" => println!("{ABOUT}"),
[cmd] if cmd == "--help" || cmd == "-h" => println!("{USAGE}"),
[cmd] if cmd == "--version" || cmd == "-V" => {
println!("aev-os {}", env!("CARGO_PKG_VERSION"))
}
[cmd, ..] if cmd == "identify" && args.len() <= 2 => {
match identify(args.get(1).map(|s| s.as_os_str())) {
Ok(true) => (),
Ok(false) => return ExitCode::from(1),
Err(error) => {
eprintln!("{error}");
return ExitCode::from(2);
}
}
}
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
ExitCode::SUCCESS
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_declared_identity() {
assert_eq!(
distribution_id("NAME=\"OS\"\nID=knottos\nID_LIKE=arch"),
Some("knottos")
);
assert_eq!(distribution_id("ID=knottos\nID='arch'"), Some("arch"));
assert_eq!(
distribution_id("ID=\"opensuse-tumbleweed\""),
Some("opensuse-tumbleweed")
);
assert_eq!(distribution_id("ID_LIKE=knottos"), None);
assert_eq!(distribution_id("ID="), None);
assert_eq!(distribution_id("ID=bad id"), None);
}
}