use std::{
fs, io,
path::{Path, PathBuf},
};
use super::platform;
pub(crate) const SYSTEMD_UNIT: &str = "rho-mcp.service";
pub(crate) const LAUNCHD_LABEL: &str = "dev.rho.mcp";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ServiceManager {
Systemd,
Launchd,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ServiceFiles {
pub(crate) manager: ServiceManager,
pub(crate) definition: PathBuf,
pub(crate) enabled_by: Vec<PathBuf>,
}
pub(crate) fn find_services(home: &Path, xdg_config_home: Option<PathBuf>) -> Vec<ServiceFiles> {
let mut found = Vec::new();
let units = xdg_config_home
.filter(|dir| dir.is_absolute())
.unwrap_or_else(|| home.join(".config"))
.join("systemd/user");
let unit = units.join(SYSTEMD_UNIT);
if unit.exists() {
let mut enabled_by: Vec<PathBuf> = fs::read_dir(&units)
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.filter(|dir| {
dir.extension()
.is_some_and(|extension| extension == "wants" || extension == "requires")
})
.map(|dir| dir.join(SYSTEMD_UNIT))
.filter(|link| link.symlink_metadata().is_ok())
.collect();
enabled_by.sort();
found.push(ServiceFiles {
manager: ServiceManager::Systemd,
definition: unit,
enabled_by,
});
}
let agent = home
.join("Library/LaunchAgents")
.join(format!("{LAUNCHD_LABEL}.plist"));
if agent.exists() {
found.push(ServiceFiles {
manager: ServiceManager::Launchd,
definition: agent,
enabled_by: Vec::new(),
});
}
found
}
impl ServiceFiles {
pub(crate) fn paths(&self) -> impl Iterator<Item = &Path> {
self.enabled_by
.iter()
.chain([&self.definition])
.map(PathBuf::as_path)
}
pub(crate) fn stop(&self) -> io::Result<()> {
platform::stop_service(self.manager)
}
pub(crate) fn delete(&self) -> io::Result<()> {
for path in self.paths() {
match fs::remove_file(path) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
Ok(())
}
}