use std::{fs, path::Path};
use crate::err::Error;
pub fn install(ctx: super::RegSvc) -> Result<(), Error> {
let service_binary_path = ::std::env::current_exe()?
.to_str()
.ok_or_else(|| Error::bad_format("Executable pathname is not utf-8"))?
.to_string();
let mut unit_lines: Vec<String> = vec![];
unit_lines.push("[Unit]".into());
if let Some(ref desc) = ctx.description {
unit_lines.push(format!("Description={desc}"));
}
if ctx.netservice {
unit_lines.push("After=network.target".into());
}
let mut svc_lines: Vec<String> = vec![];
svc_lines.push("[Service]".into());
if ctx.conf_reload {
svc_lines.push("Type=notify-reload".into());
} else {
svc_lines.push("Type=notify".into());
}
if let Some(ref username) = ctx.runas.user {
svc_lines.push(format!(r#"User="{username}""#));
}
if let Some(ref groupname) = ctx.runas.group {
svc_lines.push(format!(r#"Group="{groupname}""#));
}
if let Some(ref umask) = ctx.runas.umask {
svc_lines.push(format!(r#"UMask="{umask}""#));
}
svc_lines.push("#Restart=on-failure".to_string());
svc_lines.push("#RestartSec=5s".to_string());
if let Some(ll) = ctx.log_level {
svc_lines.push(format!(r#"Environment="LOG_LEVEL={ll}""#));
}
if let Some(lf) = ctx.log_filter {
svc_lines.push(format!(r#"Environment="LOG_FILTER={lf}""#));
}
if let Some(tf) = ctx.trace_filter {
svc_lines.push(format!(r#"Environment="TRACE_FILTER={tf}""#));
}
if let Some(fname) = ctx.trace_file {
svc_lines.push(format!(r#"Environment="TRACE_FILE={fname}""#));
}
for (key, value) in &ctx.envs {
svc_lines.push(format!(r#"Environment="{key}={value}""#));
}
if let Some(wd) = ctx.workdir {
svc_lines.push(format!("WorkingDirectory={wd}"));
}
let mut cmdline = vec![service_binary_path];
for arg in &ctx.args {
cmdline.push(arg.clone());
}
svc_lines.push(format!("ExecStart={}", cmdline.join(" ")));
let inst_lines = [
String::from("[Install]"),
String::from("WantedBy=multi-user.target")
];
let blocks = [
unit_lines.join("\n"),
svc_lines.join("\n"),
inst_lines.join("\n")
];
let mut filebuf = blocks.join("\n\n");
filebuf.push('\n');
let fname = format!("{}.service", ctx.svcname);
let fname = Path::new(&fname);
if fname.exists() && !ctx.force {
Err(Error::io("File already exists."))?;
}
fs::write(fname, filebuf)?;
Ok(())
}
#[expect(clippy::missing_errors_doc)]
#[expect(clippy::missing_const_for_fn)]
pub fn uninstall(_svcname: &str) -> Result<(), Error> {
Ok(())
}