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(ServiceOptions),
Uninstall(ServiceOptions),
Start(ServiceOptions),
Stop(ServiceOptions),
Status(ServiceOptions),
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 {
#[arg(long)]
pub name: Option<String>,
#[arg(long, value_enum, default_value_t = ServiceScope::System)]
pub scope: ServiceScope,
#[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,
},
)
}