use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
pub(crate) fn locate_binaries() -> Result<(PathBuf, PathBuf, PathBuf)> {
let cli_exe = std::env::current_exe().context("cannot determine own binary path")?;
let bin_dir = cli_exe.parent().unwrap();
let api_bin = locate_beside(bin_dir, "second-brain-api")?;
let mcp_bin = locate_beside(bin_dir, "second-brain-mcp")?;
Ok((api_bin, mcp_bin, cli_exe))
}
pub(crate) fn locate_beside(bin_dir: &Path, name: &str) -> Result<PathBuf> {
let candidate = bin_dir.join(name);
if candidate.exists() {
Ok(candidate)
} else {
which_bin(name)
}
}
fn which_bin(name: &str) -> Result<PathBuf> {
let home = std::env::var("HOME").unwrap_or_default();
let cargo_bin = PathBuf::from(&home).join(".cargo/bin").join(name);
if cargo_bin.exists() {
return Ok(cargo_bin);
}
let output = std::process::Command::new("which")
.arg(name)
.output()
.context(format!("{name} not found"))?;
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(PathBuf::from(path))
} else {
anyhow::bail!(
"{name} not found in PATH or ~/.cargo/bin — install with: cargo install {name}"
)
}
}