luciola-cli 0.14.0

Command-line interface and diagnostic radar for the Luciola P2P discovery engine
//! Cross-platform user-level background service management for `luciola agent`.
//!
//! Generates standard manifests for macOS (`launchd` LaunchAgent), Linux
//! (`systemd --user`), and Windows (Task Scheduler XML) using runtime-resolved
//! executable and home paths (never hardcoded machine paths).

use std::path::{Path, PathBuf};

/// macOS LaunchAgent label.
pub const MACOS_SERVICE_LABEL: &str = "io.github.kexuejin.luciola.agent";
/// Linux systemd user unit filename.
pub const LINUX_SERVICE_UNIT: &str = "luciola-agent.service";

/// Target OS kind for manifest rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub enum ServicePlatform {
    /// macOS LaunchAgent (`launchd`).
    MacOs,
    /// Linux user-level `systemd`.
    Linux,
    /// Windows Task Scheduler XML.
    Windows,
}

impl ServicePlatform {
    /// Detect the current build target platform.
    pub fn current() -> Self {
        #[cfg(target_os = "macos")]
        {
            Self::MacOs
        }
        #[cfg(target_os = "linux")]
        {
            Self::Linux
        }
        #[cfg(target_os = "windows")]
        {
            Self::Windows
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
        {
            Self::Linux
        }
    }
}

/// Configuration rendered into a platform daemon manifest.
#[derive(Debug, Clone)]
pub struct ServiceSpec {
    /// Absolute path to the `luciola-cli` binary.
    pub binary_path: PathBuf,
    /// Discovery UDP port passed to `agent --port`.
    pub port: u16,
    /// Optional unix socket override passed to `agent --socket`.
    pub socket: Option<String>,
    /// Optional log directory for stdout/stderr redirection.
    pub log_dir: PathBuf,
}

impl ServiceSpec {
    /// Build CLI arguments for the `agent` subcommand.
    pub fn agent_args(&self) -> Vec<String> {
        let mut args = vec![
            "agent".to_string(),
            "--port".to_string(),
            self.port.to_string(),
        ];
        if let Some(ref sock) = self.socket {
            args.push("--socket".to_string());
            args.push(sock.clone());
        }
        args
    }
}

fn xml_escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// Render a macOS `launchd` LaunchAgent plist.
pub fn render_launchd_plist(spec: &ServiceSpec) -> String {
    let mut program_args = format!(
        "    <string>{}</string>\n",
        xml_escape(&spec.binary_path.to_string_lossy())
    );
    for arg in spec.agent_args() {
        program_args.push_str(&format!("    <string>{}</string>\n", xml_escape(&arg)));
    }
    let stdout = spec.log_dir.join("luciola-agent.out.log");
    let stderr = spec.log_dir.join("luciola-agent.err.log");
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>{MACOS_SERVICE_LABEL}</string>
  <key>ProgramArguments</key>
  <array>
{program_args}  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>{stdout}</string>
  <key>StandardErrorPath</key>
  <string>{stderr}</string>
</dict>
</plist>
"#,
        stdout = xml_escape(&stdout.to_string_lossy()),
        stderr = xml_escape(&stderr.to_string_lossy()),
    )
}

fn systemd_quote(arg: &str) -> String {
    let mut out = String::with_capacity(arg.len() + 2);
    out.push('"');
    for ch in arg.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '%' => out.push_str("%%"),
            '\n' | '\r' | '\0' => {}
            _ => out.push(ch),
        }
    }
    out.push('"');
    out
}

fn windows_quote_arg(arg: &str) -> String {
    if !arg.is_empty() && !arg.chars().any(|c| c.is_whitespace() || c == '"') {
        return arg.to_string();
    }
    let escaped = arg.replace('"', "\\\"");
    format!("\"{escaped}\"")
}

/// Render a Linux `systemd --user` unit file.
pub fn render_systemd_unit(spec: &ServiceSpec) -> String {
    let mut exec = systemd_quote(&spec.binary_path.to_string_lossy());
    for arg in spec.agent_args() {
        exec.push(' ');
        exec.push_str(&systemd_quote(&arg));
    }
    format!(
        r#"[Unit]
Description=Luciola Discovery Agent
After=network-online.target

[Service]
Type=simple
ExecStart={exec}
Restart=on-failure
RestartSec=3

[Install]
WantedBy=default.target
"#
    )
}

/// Render a Windows Task Scheduler XML definition (UTF-8 encoded).
pub fn render_windows_task_xml(spec: &ServiceSpec) -> String {
    let cmd = xml_escape(&spec.binary_path.to_string_lossy());
    let joined_args = spec
        .agent_args()
        .iter()
        .map(|a| windows_quote_arg(a))
        .collect::<Vec<_>>()
        .join(" ");
    let args = xml_escape(&joined_args);
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <RestartOnFailure>
      <Interval>PT1M</Interval>
      <Count>3</Count>
    </RestartOnFailure>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>{cmd}</Command>
      <Arguments>{args}</Arguments>
    </Exec>
  </Actions>
</Task>
"#
    )
}

/// Render the manifest for `platform`.
pub fn render_manifest(platform: ServicePlatform, spec: &ServiceSpec) -> String {
    match platform {
        ServicePlatform::MacOs => render_launchd_plist(spec),
        ServicePlatform::Linux => render_systemd_unit(spec),
        ServicePlatform::Windows => render_windows_task_xml(spec),
    }
}

/// Resolve the user's home directory from `HOME` or `USERPROFILE`.
pub fn resolve_home_dir() -> Result<PathBuf, String> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .ok_or_else(|| "cannot resolve user home directory (HOME/USERPROFILE unset)".into())
}

/// Resolve the standard user-level manifest path for `platform`.
pub fn manifest_path(platform: ServicePlatform, home: &Path) -> PathBuf {
    match platform {
        ServicePlatform::MacOs => home
            .join("Library")
            .join("LaunchAgents")
            .join(format!("{MACOS_SERVICE_LABEL}.plist")),
        ServicePlatform::Linux => home
            .join(".config")
            .join("systemd")
            .join("user")
            .join(LINUX_SERVICE_UNIT),
        ServicePlatform::Windows => home.join(".luciola").join("luciola-agent-task.xml"),
    }
}

/// Install the user-level background service manifest on the current machine.
pub fn install_service(port: u16, socket: Option<String>) -> Result<PathBuf, String> {
    let home = resolve_home_dir()?;
    let binary_path =
        std::env::current_exe().map_err(|e| format!("resolve current executable: {e}"))?;
    let log_dir = home.join(".luciola").join("logs");
    std::fs::create_dir_all(&log_dir).map_err(|e| format!("create log dir: {e}"))?;

    let platform = ServicePlatform::current();
    let spec = ServiceSpec {
        binary_path,
        port,
        socket,
        log_dir,
    };
    let path = manifest_path(platform, &home);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| format!("create manifest dir: {e}"))?;
    }
    let content = render_manifest(platform, &spec);
    std::fs::write(&path, content)
        .map_err(|e| format!("write manifest {}: {e}", path.display()))?;

    #[cfg(target_os = "macos")]
    {
        let _ = std::process::Command::new("launchctl")
            .args(["unload", "-w"])
            .arg(&path)
            .status();
        let status = std::process::Command::new("launchctl")
            .args(["load", "-w"])
            .arg(&path)
            .status()
            .map_err(|e| format!("launchctl load: {e}"))?;
        if !status.success() {
            return Err(format!("launchctl load exited with {status}"));
        }
    }

    #[cfg(target_os = "linux")]
    {
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "daemon-reload"])
            .status();
        let status = std::process::Command::new("systemctl")
            .args(["--user", "enable", "--now", LINUX_SERVICE_UNIT])
            .status()
            .map_err(|e| format!("systemctl enable: {e}"))?;
        if !status.success() {
            return Err(format!("systemctl enable exited with {status}"));
        }
    }

    #[cfg(target_os = "windows")]
    {
        let status = std::process::Command::new("schtasks")
            .args(["/Create", "/TN", "LuciolaAgent", "/XML"])
            .arg(&path)
            .arg("/F")
            .status()
            .map_err(|e| format!("schtasks /Create: {e}"))?;
        if !status.success() {
            return Err(format!("schtasks /Create exited with {status}"));
        }
    }

    Ok(path)
}

/// Stop and remove the user-level background service manifest.
pub fn uninstall_service() -> Result<PathBuf, String> {
    let home = resolve_home_dir()?;
    let platform = ServicePlatform::current();
    let path = manifest_path(platform, &home);

    #[cfg(target_os = "macos")]
    {
        if path.exists() {
            let _ = std::process::Command::new("launchctl")
                .args(["unload", "-w"])
                .arg(&path)
                .status();
        }
    }

    #[cfg(target_os = "linux")]
    {
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "disable", "--now", LINUX_SERVICE_UNIT])
            .status();
    }

    #[cfg(target_os = "windows")]
    {
        let _ = std::process::Command::new("schtasks")
            .args(["/Delete", "/TN", "LuciolaAgent", "/F"])
            .status();
    }

    if path.exists() {
        std::fs::remove_file(&path)
            .map_err(|e| format!("remove manifest {}: {e}", path.display()))?;
    }
    Ok(path)
}

/// Report whether the user-level background service manifest is installed.
pub fn service_status() -> Result<(PathBuf, bool), String> {
    let home = resolve_home_dir()?;
    let path = manifest_path(ServicePlatform::current(), &home);
    let installed = path.exists();
    Ok((path, installed))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_spec() -> ServiceSpec {
        ServiceSpec {
            binary_path: PathBuf::from("/usr/local/bin/luciola-cli"),
            port: 17878,
            socket: Some("/tmp/luciola.sock".into()),
            log_dir: PathBuf::from("/var/tmp/luciola-logs"),
        }
    }

    #[test]
    fn launchd_plist_renders_expected_keys_and_escapes_xml() {
        let mut spec = sample_spec();
        spec.socket = Some("/tmp/a&b.sock".into());
        let plist = render_launchd_plist(&spec);
        assert!(plist.contains(MACOS_SERVICE_LABEL));
        assert!(plist.contains("<string>agent</string>"));
        assert!(plist.contains("<string>/tmp/a&amp;b.sock</string>"));
        assert!(plist.contains("<key>KeepAlive</key>"));
    }

    #[test]
    fn systemd_unit_and_windows_xml_render_valid_manifests() {
        let mut spec = sample_spec();
        spec.socket = Some("/tmp/my %dir/luciola.sock".into());
        let unit = render_systemd_unit(&spec);
        assert!(unit.contains(
            "ExecStart=\"/usr/local/bin/luciola-cli\" \"agent\" \"--port\" \"17878\" \"--socket\" \"/tmp/my %%dir/luciola.sock\""
        ));
        assert!(unit.contains("Restart=on-failure"));

        let xml = render_windows_task_xml(&spec);
        assert!(xml.contains("encoding=\"UTF-8\""));
        assert!(xml.contains("<Command>/usr/local/bin/luciola-cli</Command>"));
        assert!(xml.contains("&quot;/tmp/my %dir/luciola.sock&quot;"));
    }
}