troll 0.3.2

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
//! Platform-dispatched installation and activation of the background user service.

use std::{
    io::{self, Write},
    path::{Path, PathBuf},
    process::ExitStatus,
};

use serde::Serialize;

mod launchd;
pub(crate) mod plugins;
mod scheduled_task;
#[cfg(target_os = "linux")]
mod systemd;

use crate::{error::CliError, output, platform};

pub(crate) struct Unit {
    pub(crate) path: PathBuf,
    #[cfg(target_os = "linux")]
    inner: systemd::SystemdUnit,
    #[cfg(target_os = "macos")]
    inner: launchd::LaunchdAgent,
    #[cfg(target_os = "windows")]
    inner: scheduled_task::ScheduledTask,
}

impl Unit {
    pub(crate) fn for_homes(config_home: &Path, state_home: &Path) -> Result<Self, CliError> {
        #[cfg(target_os = "linux")]
        {
            let inner = systemd::SystemdUnit::for_homes(config_home, state_home)?;
            let path = inner.path.clone();
            Ok(Self { path, inner })
        }
        #[cfg(target_os = "macos")]
        {
            let inner = launchd::LaunchdAgent::for_homes(config_home, state_home)?;
            let path = inner.path.clone();
            Ok(Self { path, inner })
        }
        #[cfg(target_os = "windows")]
        {
            let inner = scheduled_task::ScheduledTask::for_homes(config_home, state_home)?;
            let path = inner.path.clone();
            Ok(Self { path, inner })
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            let _ = (config_home, state_home);
            Err(CliError::Unsupported(
                "`troll setup service` is not implemented for this platform yet.",
            ))
        }
    }

    /// Preview without creating a directory or altering an existing unit.
    pub(crate) fn check(&self) -> Result<(), CliError> {
        #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
        {
            self.inner.check()
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            Err(CliError::Unsupported(
                "`troll setup service` is not implemented for this platform yet.",
            ))
        }
    }

    pub(crate) fn install(&self, force: bool) -> Result<ServiceResult, CliError> {
        #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
        {
            self.inner.install(force)
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            let _ = force;
            Err(CliError::Unsupported(
                "`troll setup service` is not implemented for this platform yet.",
            ))
        }
    }
}

pub(crate) fn run(force: bool, json: bool) -> Result<(), CliError> {
    let result =
        Unit::for_homes(&platform::config_home()?, &platform::state_home()?)?.install(force)?;
    #[derive(Serialize)]
    struct SetupOutput<'a> {
        schema: u32,
        #[serde(flatten)]
        service: &'a ServiceResult,
    }
    output::write(
        json,
        &SetupOutput {
            schema: output::SCHEMA,
            service: &result,
        },
        |out| result.write_human(out),
    )
}

pub(crate) trait Systemctl {
    fn run(&mut self, args: &[&str]) -> io::Result<ExitStatus>;
}

pub(crate) struct SystemctlProcess;

impl Systemctl for SystemctlProcess {
    fn run(&mut self, args: &[&str]) -> io::Result<ExitStatus> {
        #[cfg(target_os = "linux")]
        {
            systemd::run_systemctl(args)
        }
        #[cfg(target_os = "macos")]
        {
            launchd::run_launchctl(args)
        }
        #[cfg(target_os = "windows")]
        {
            scheduled_task::run_schtasks(args)
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            let _ = args;
            Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "service activation is unsupported on this platform",
            ))
        }
    }
}

#[derive(Serialize)]
pub(crate) struct ServiceResult {
    #[serde(skip)]
    pub(super) kind_label: &'static str,
    pub(super) path: String,
    pub(crate) status: &'static str,
    pub(super) next_commands: Vec<String>,
    pub(super) activation: Vec<CommandResult>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(super) note: Option<&'static str>,
}

#[derive(Serialize)]
pub(super) struct CommandResult {
    pub(super) command: String,
    pub(super) success: bool,
    pub(super) exit_code: Option<i32>,
    pub(super) status: String,
}

impl ServiceResult {
    pub(crate) fn activate(&mut self, runner: &mut dyn Systemctl) {
        #[cfg(target_os = "linux")]
        systemd::activate(self, runner);
        #[cfg(target_os = "macos")]
        launchd::activate(self, runner);
        #[cfg(target_os = "windows")]
        scheduled_task::activate(self, runner);
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            let _ = runner;
        }
    }

    pub(crate) fn write_human(&self, out: &mut dyn Write) -> Result<(), CliError> {
        writeln!(out, "{} {:?}: {}.", self.kind_label, self.path, self.status)?;
        if let Some(note) = self.note {
            writeln!(out, "{note}")?;
        }
        for command in &self.activation {
            writeln!(out, "{}: {}.", command.command, command.status)?;
        }
        if !self.next_commands.is_empty() {
            writeln!(out, "To start the service, run:")?;
            for command in &self.next_commands {
                writeln!(out, "  {command}")?;
            }
        }
        Ok(())
    }
}