xtask_toolkit/
linux_utils.rs

1use std::path::{Path, PathBuf};
2
3pub struct LinuxUser(pub String);
4pub struct LinuxGroup(pub String);
5
6impl LinuxUser {
7    pub fn bash_add(&self) -> String {
8        format!(
9            r#"
10        if [ -z "$(getent passwd | grep {account})" ]; then 
11            useradd -r {account};
12        fi
13    "#,
14            account = &self.0
15        )
16    }
17
18    pub fn bash_remove(&self) -> String {
19        format!("userdel -r {};", &self.0)
20    }
21}
22
23impl LinuxGroup {
24    pub fn bash_add(&self) -> String {
25        format!(
26            r#"
27        if [ -z "$(getent group | grep {group})" ]; then 
28            groupadd -r {group};
29        fi
30    "#,
31            group = &self.0
32        )
33    }
34
35    pub fn bash_remove(&self) -> String {
36        format!("groupdel {};", &self.0)
37    }
38}
39
40#[derive(Debug)]
41pub struct SystemdUnit(pub String);
42
43impl TryFrom<&Path> for SystemdUnit
44{
45    type Error = ();
46
47    fn try_from(value: &Path) -> Result<Self, Self::Error> {
48        Ok(Self(
49            value
50                .file_name()
51                .ok_or(())?
52                .to_string_lossy()
53                .to_string(),
54        ))
55    }
56}
57
58impl TryFrom<&PathBuf> for SystemdUnit
59{
60    type Error = ();
61
62    fn try_from(value: &PathBuf) -> Result<Self, Self::Error> {
63        Self::try_from(value.as_path())
64    }
65}
66
67impl SystemdUnit {
68    pub fn bash_reload_daemon() -> String {
69        format!("systemctl daemon-reload;")
70    }
71
72    pub fn bash_disable_and_stop(&self) -> String {
73        let unit = &self.0;
74        format!(
75            r#"
76            if [ $(systemctl list-unit-files {unit} &> /dev/null; echo $?) -eq 0 ]; then
77                systemctl disable {unit};
78                systemctl stop {unit};
79            fi;
80        "#
81        )
82    }
83
84    pub fn bash_restart_if_active(&self) -> String {
85        format!(
86            "systemctl is-active --quiet {} && systemctl restart {};",
87            &self.0, &self.0
88        )
89    }
90}