//! Getǣl CLI entrypoint. use anyhow::{Context, bail}; use clap::{Parser, Subcommand}; use getael::cache::CacheStore; use getael::config::Config; use getael::engine::Engine; use getael::macos::{default_snapshot_provider, default_volume_telemetry}; use getael::scanner::{ApfsScanner, Scanner, current_time_ns}; use getael::server; use getael::service; use getael::tray; use getael::watcher::NativeFsWatcher; use std::io::{Read, Write}; use std::net::{IpAddr, SocketAddr, TcpStream}; use std::sync::Arc; use std::time::Duration; use tracing::info; use tracing_subscriber::EnvFilter; #[derive(Debug, Parser)] #[command( name = "getael", version, about = "Strictly read-only macOS APFS storage cartography" )] struct Cli { #[command(subcommand)] command: Option, } #[derive(Debug, Subcommand)] enum Command { /// Run the read-only HTTP server and live `FSEvents` monitor. Serve { #[arg(long)] port: Option, #[arg(long)] host: Option, #[arg(long)] open: bool, }, /// Run the read-only HTTP server alongside a native menubar / system tray icon. Tray { #[arg(long)] port: Option, #[arg(long)] host: Option, #[arg(long)] open: bool, }, /// Run a one-shot full scan of the Home Root and update the SQLite cache. Scan { #[arg(long)] json: bool, }, /// Query status of the local Getǣl service. Status { #[arg(long)] json: bool, }, /// Manage the macOS `LaunchAgent` background service. Service { #[command(subcommand)] action: ServiceAction, }, } #[derive(Debug, Subcommand)] enum ServiceAction { /// Install and load `~/Library/LaunchAgents/local.getael.plist`. Install { #[arg(long)] port: Option, }, /// Unload and remove `~/Library/LaunchAgents/local.getael.plist`. Uninstall, /// Check `launchd` and HTTP health status. Status, } fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() .with_env_filter( EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), ) .init(); let cli = Cli::parse(); let mut cfg = Config::load()?; match cli.command.unwrap_or(Command::Serve { port: None, host: None, open: false, }) { Command::Serve { port, host, open } => { apply_bind_overrides(&mut cfg, port, host)?; let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .context("failed to initialize Tokio runtime")?; rt.block_on(run_serve(cfg, open)) } Command::Tray { port, host, open } => { apply_bind_overrides(&mut cfg, port, host)?; tray::run_tray(cfg, open) } Command::Scan { json } => run_scan(&cfg, json), Command::Status { json } => run_status(&cfg, json), Command::Service { action } => run_service(&cfg, &action), } } fn apply_bind_overrides( cfg: &mut Config, port: Option, host: Option, ) -> anyhow::Result<()> { if let Some(p) = port { if p == 0 { bail!("invalid port 0: must be between 1 and 65535"); } cfg.port = p; } if let Some(h) = host { if !h.is_loopback() { bail!("refusing to bind non-loopback address {h}"); } cfg.host = h; } Ok(()) } async fn run_serve(cfg: Config, open_browser: bool) -> anyhow::Result<()> { let addr = SocketAddr::new(cfg.host, cfg.port); // Bind listener before opening cache / starting background scan or FSEvents watcher (no TOCTOU). let listener = tokio::net::TcpListener::bind(addr).await.map_err(|err| { if err.kind() == std::io::ErrorKind::AddrInUse { anyhow::anyhow!( "port {} on {} is already in use; is Getǣl already running?", cfg.port, cfg.host ) } else { anyhow::Error::new(err).context(format!("failed to bind {addr}")) } })?; let cfg_arc = Arc::new(cfg); let cache = Arc::new(CacheStore::open(&cfg_arc.cache_path)?); let scanner = Arc::new(ApfsScanner::new()); let vol = default_volume_telemetry(); let snaps = default_snapshot_provider(); let watcher = Arc::new(NativeFsWatcher::new()); let engine = Arc::new(Engine::new( Arc::clone(&cfg_arc), cache, scanner, vol, snaps, watcher, )); let handle = engine.start(true)?; info!("Getǣl listening on http://{addr}"); if open_browser { tray::open_url_in_browser(&format!("http://{addr}")); } let serve_res = server::serve_listener(Arc::clone(&engine), listener).await; handle.shutdown(); serve_res.context("HTTP server exited with error") } fn run_scan(cfg: &Config, json: bool) -> anyhow::Result<()> { let started_ns = current_time_ns(); let scanner = ApfsScanner::new(); let scan = scanner.scan_full(&cfg.home_root, &|_| {})?; let completed_ns = current_time_ns(); let cache = CacheStore::open(&cfg.cache_path)?; cache.replace_full_scan(&scan, &cfg.home_root, started_ns, completed_ns)?; if json { println!("{}", serde_json::to_string_pretty(&scan.progress)?); } else { println!( "Scanned {} dirs, {} files ({} physical bytes, {} logical bytes, {} inaccessible)", scan.progress.scanned_dirs, scan.progress.scanned_files, scan.progress.scanned_physical_bytes, scan.progress.scanned_logical_bytes, scan.progress.inaccessible_dirs ); } Ok(()) } fn run_status(cfg: &Config, json: bool) -> anyhow::Result<()> { let addr = SocketAddr::new(cfg.host, cfg.port); if let Some(body) = http_get_local(addr, "/api/health") { if json { println!("{body}"); } else { println!("Getǣl running at http://{addr}\n{body}"); } return Ok(()); } let cache_info = if cfg.cache_path.exists() { let store = CacheStore::open_read_only(&cfg.cache_path)?; let meta = store.meta()?; format!( "stopped (last scan completed ns: {})", meta.last_full_scan_completed_ns ) } else { "stopped (no cache yet)".to_string() }; if json { println!( "{}", serde_json::json!({ "status": "stopped", "detail": cache_info }) ); } else { println!("Getǣl status: {cache_info}"); } Ok(()) } fn run_service(cfg: &Config, action: &ServiceAction) -> anyhow::Result<()> { match action { ServiceAction::Install { port } => { let real_home = dirs::home_dir().context("unable to determine home directory")?; let p = port.unwrap_or(cfg.port); if p == 0 { bail!("invalid port 0: must be between 1 and 65535"); } let plist = service::install(&real_home, &cfg.log_dir, p)?; println!("Installed and loaded LaunchAgent at {}", plist.display()); } ServiceAction::Uninstall => { let real_home = dirs::home_dir().context("unable to determine home directory")?; service::uninstall(&real_home)?; println!("Unloaded and removed LaunchAgent plist"); } ServiceAction::Status => { let loaded = service::is_service_loaded(); let addr = SocketAddr::new(cfg.host, cfg.port); let http_up = http_get_local(addr, "/api/health").is_some(); println!( "service: {}, http (http://{addr}): {}", if loaded { "loaded" } else { "not loaded" }, if http_up { "healthy" } else { "unreachable" } ); } } Ok(()) } fn http_get_local(addr: SocketAddr, path: &str) -> Option { let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500)).ok()?; let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); let req = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n"); stream.write_all(req.as_bytes()).ok()?; let mut buf = String::new(); stream.read_to_string(&mut buf).ok()?; let (head, body) = buf.split_once("\r\n\r\n")?; let status_line = head.lines().next()?; let code = status_line.split_whitespace().nth(1)?; if code != "200" { return None; } let parsed: serde_json::Value = serde_json::from_str(body.trim()).ok()?; if parsed.get("status").and_then(|s| s.as_str()) != Some("ok") { return None; } Some(body.to_string()) }