device-daemon-core 0.0.2

Reusable async daemon and MQTT infrastructure for device clients
Documentation
use crate::service::{
    self, ServiceAction as CoreServiceAction, ServiceDefinition, ServiceLaunch,
    ServiceScope as CoreServiceScope,
};
use anyhow::Result;
use clap::{Args, Subcommand, ValueEnum};
use std::path::Path;

#[derive(Subcommand, Debug, Clone, PartialEq)]
pub enum ServiceAction {
    /// Install and start this service instance.
    Install(ServiceOptions),
    /// Stop and remove this service instance.
    Uninstall(ServiceOptions),
    /// Start an installed service.
    Start(ServiceOptions),
    /// Stop an installed service.
    Stop(ServiceOptions),
    /// Show one service status, or all matching services if no name is given.
    Status(ServiceOptions),
    /// List matching services.
    List(ServiceOptions),
}

impl ServiceAction {
    pub fn as_core_parts(&self) -> (CoreServiceAction, &ServiceOptions) {
        match self {
            Self::Install(options) => (CoreServiceAction::Install, options),
            Self::Uninstall(options) => (CoreServiceAction::Uninstall, options),
            Self::Start(options) => (CoreServiceAction::Start, options),
            Self::Stop(options) => (CoreServiceAction::Stop, options),
            Self::Status(options) => (CoreServiceAction::Status, options),
            Self::List(options) => (CoreServiceAction::List, options),
        }
    }
}

#[derive(Args, Debug, Clone, PartialEq)]
pub struct ServiceOptions {
    /// Service name. Install defaults to the application name; list accepts a name prefix.
    #[arg(long)]
    pub name: Option<String>,
    /// Service scope.
    #[arg(long, value_enum, default_value_t = ServiceScope::System)]
    pub scope: ServiceScope,
    /// Account to run a system-wide service as; required for install.
    #[arg(long)]
    pub run_as: Option<String>,
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ServiceScope {
    User,
    #[default]
    System,
}

impl ServiceScope {
    pub fn into_core_scope(self) -> CoreServiceScope {
        match self {
            Self::User => CoreServiceScope::User,
            Self::System => CoreServiceScope::System,
        }
    }
}

pub fn manage_configured_service(
    action: CoreServiceAction,
    application: &str,
    options: &ServiceOptions,
    config_path: &Path,
    launch_args: &[&str],
) -> Result<()> {
    let launch = if matches!(action, CoreServiceAction::Install) {
        let mut builder = ServiceLaunch::builder(config_path)?;
        for arg in launch_args {
            builder = builder.arg(*arg);
        }
        Some(builder.build())
    } else {
        None
    };

    service::manage(
        action,
        &ServiceDefinition {
            application: application.to_owned(),
            name: options.name.clone(),
            scope: options.scope.into_core_scope(),
            run_as: options.run_as.clone(),
            launch,
        },
    )
}