1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright (C) 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use color_eyre::{eyre::eyre, Result};
use libp2p::Multiaddr;
use service_manager::{ServiceInstallCtx, ServiceLabel};
use sn_logging::LogFormat;
use std::{
    ffi::OsString,
    net::{Ipv4Addr, SocketAddr},
    path::PathBuf,
    str::FromStr,
};

#[derive(Clone, Debug)]
pub enum PortRange {
    Single(u16),
    Range(u16, u16),
}

impl PortRange {
    pub fn parse(s: &str) -> Result<Self> {
        if let Ok(port) = u16::from_str(s) {
            Ok(Self::Single(port))
        } else {
            let parts: Vec<&str> = s.split('-').collect();
            if parts.len() != 2 {
                return Err(eyre!("Port range must be in the format 'start-end'"));
            }
            let start = parts[0].parse::<u16>()?;
            let end = parts[1].parse::<u16>()?;
            if start >= end {
                return Err(eyre!("End port must be greater than start port"));
            }
            Ok(Self::Range(start, end))
        }
    }

    /// Validate the port range against a count to make sure the correct number of ports are provided.
    pub fn validate(&self, count: u16) -> Result<()> {
        match self {
            Self::Single(_) => {
                if count != 1 {
                    error!("The count ({count}) does not match the number of ports (1)");
                    return Err(eyre!(
                        "The count ({count}) does not match the number of ports (1)"
                    ));
                }
            }
            Self::Range(start, end) => {
                let port_count = end - start + 1;
                if count != port_count {
                    error!("The count ({count}) does not match the number of ports ({port_count})");
                    return Err(eyre!(
                        "The count ({count}) does not match the number of ports ({port_count})"
                    ));
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, PartialEq)]
pub struct InstallNodeServiceCtxBuilder {
    pub autostart: bool,
    pub bootstrap_peers: Vec<Multiaddr>,
    pub data_dir_path: PathBuf,
    pub env_variables: Option<Vec<(String, String)>>,
    pub genesis: bool,
    pub home_network: bool,
    pub local: bool,
    pub log_dir_path: PathBuf,
    pub log_format: Option<LogFormat>,
    pub name: String,
    pub metrics_port: Option<u16>,
    pub node_port: Option<u16>,
    pub owner: Option<String>,
    pub rpc_socket_addr: SocketAddr,
    pub safenode_path: PathBuf,
    pub service_user: Option<String>,
    pub upnp: bool,
}

impl InstallNodeServiceCtxBuilder {
    pub fn build(self) -> Result<ServiceInstallCtx> {
        let label: ServiceLabel = self.name.parse()?;
        let mut args = vec![
            OsString::from("--rpc"),
            OsString::from(self.rpc_socket_addr.to_string()),
            OsString::from("--root-dir"),
            OsString::from(self.data_dir_path.to_string_lossy().to_string()),
            OsString::from("--log-output-dest"),
            OsString::from(self.log_dir_path.to_string_lossy().to_string()),
        ];

        if self.genesis {
            args.push(OsString::from("--first"));
        }
        if self.home_network {
            args.push(OsString::from("--home-network"));
        }
        if self.local {
            args.push(OsString::from("--local"));
        }
        if let Some(log_format) = self.log_format {
            args.push(OsString::from("--log-format"));
            args.push(OsString::from(log_format.as_str()));
        }
        if self.upnp {
            args.push(OsString::from("--upnp"));
        }
        if let Some(node_port) = self.node_port {
            args.push(OsString::from("--port"));
            args.push(OsString::from(node_port.to_string()));
        }
        if let Some(metrics_port) = self.metrics_port {
            args.push(OsString::from("--metrics-server-port"));
            args.push(OsString::from(metrics_port.to_string()));
        }
        if let Some(owner) = self.owner {
            args.push(OsString::from("--owner"));
            args.push(OsString::from(owner));
        }

        if !self.bootstrap_peers.is_empty() {
            let peers_str = self
                .bootstrap_peers
                .iter()
                .map(|peer| peer.to_string())
                .collect::<Vec<_>>()
                .join(",");
            args.push(OsString::from("--peer"));
            args.push(OsString::from(peers_str));
        }

        Ok(ServiceInstallCtx {
            args,
            autostart: self.autostart,
            contents: None,
            environment: self.env_variables,
            label: label.clone(),
            program: self.safenode_path.to_path_buf(),
            username: self.service_user.clone(),
            working_directory: None,
        })
    }
}

pub struct AddNodeServiceOptions {
    pub auto_restart: bool,
    pub auto_set_nat_flags: bool,
    pub bootstrap_peers: Vec<Multiaddr>,
    pub count: Option<u16>,
    pub delete_safenode_src: bool,
    pub enable_metrics_server: bool,
    pub env_variables: Option<Vec<(String, String)>>,
    pub genesis: bool,
    pub home_network: bool,
    pub local: bool,
    pub log_format: Option<LogFormat>,
    pub metrics_port: Option<PortRange>,
    pub owner: Option<String>,
    pub node_port: Option<PortRange>,
    pub rpc_address: Option<Ipv4Addr>,
    pub rpc_port: Option<PortRange>,
    pub safenode_src_path: PathBuf,
    pub safenode_dir_path: PathBuf,
    pub service_data_dir_path: PathBuf,
    pub service_log_dir_path: PathBuf,
    pub upnp: bool,
    pub user: Option<String>,
    pub user_mode: bool,
    pub version: String,
}

#[derive(Debug, PartialEq)]
pub struct InstallAuditorServiceCtxBuilder {
    pub auditor_path: PathBuf,
    pub beta_encryption_key: Option<String>,
    pub bootstrap_peers: Vec<Multiaddr>,
    pub env_variables: Option<Vec<(String, String)>>,
    pub log_dir_path: PathBuf,
    pub name: String,
    pub service_user: String,
}

impl InstallAuditorServiceCtxBuilder {
    pub fn build(self) -> Result<ServiceInstallCtx> {
        let mut args = vec![
            OsString::from("--log-output-dest"),
            OsString::from(self.log_dir_path.to_string_lossy().to_string()),
        ];

        if !self.bootstrap_peers.is_empty() {
            let peers_str = self
                .bootstrap_peers
                .iter()
                .map(|peer| peer.to_string())
                .collect::<Vec<_>>()
                .join(",");
            args.push(OsString::from("--peer"));
            args.push(OsString::from(peers_str));
        }
        if let Some(beta_encryption_key) = self.beta_encryption_key {
            args.push(OsString::from("--beta-encryption-key"));
            args.push(OsString::from(beta_encryption_key));
        }

        Ok(ServiceInstallCtx {
            args,
            autostart: true,
            contents: None,
            environment: self.env_variables,
            label: self.name.parse()?,
            program: self.auditor_path.to_path_buf(),
            username: Some(self.service_user.to_string()),
            working_directory: None,
        })
    }
}

#[derive(Debug, PartialEq)]
pub struct InstallFaucetServiceCtxBuilder {
    pub bootstrap_peers: Vec<Multiaddr>,
    pub env_variables: Option<Vec<(String, String)>>,
    pub faucet_path: PathBuf,
    pub local: bool,
    pub log_dir_path: PathBuf,
    pub name: String,
    pub service_user: String,
}

impl InstallFaucetServiceCtxBuilder {
    pub fn build(self) -> Result<ServiceInstallCtx> {
        let mut args = vec![
            OsString::from("--log-output-dest"),
            OsString::from(self.log_dir_path.to_string_lossy().to_string()),
        ];

        if !self.bootstrap_peers.is_empty() {
            let peers_str = self
                .bootstrap_peers
                .iter()
                .map(|peer| peer.to_string())
                .collect::<Vec<_>>()
                .join(",");
            args.push(OsString::from("--peer"));
            args.push(OsString::from(peers_str));
        }

        args.push(OsString::from("server"));

        Ok(ServiceInstallCtx {
            args,
            autostart: true,
            contents: None,
            environment: self.env_variables,
            label: self.name.parse()?,
            program: self.faucet_path.to_path_buf(),
            username: Some(self.service_user.to_string()),
            working_directory: None,
        })
    }
}

pub struct AddAuditorServiceOptions {
    pub auditor_install_bin_path: PathBuf,
    pub auditor_src_bin_path: PathBuf,
    pub beta_encryption_key: Option<String>,
    pub bootstrap_peers: Vec<Multiaddr>,
    pub env_variables: Option<Vec<(String, String)>>,
    pub service_log_dir_path: PathBuf,
    pub user: String,
    pub version: String,
}

pub struct AddFaucetServiceOptions {
    pub bootstrap_peers: Vec<Multiaddr>,
    pub env_variables: Option<Vec<(String, String)>>,
    pub faucet_install_bin_path: PathBuf,
    pub faucet_src_bin_path: PathBuf,
    pub local: bool,
    pub service_data_dir_path: PathBuf,
    pub service_log_dir_path: PathBuf,
    pub user: String,
    pub version: String,
}

pub struct AddDaemonServiceOptions {
    pub address: Ipv4Addr,
    pub env_variables: Option<Vec<(String, String)>>,
    pub daemon_install_bin_path: PathBuf,
    pub daemon_src_bin_path: PathBuf,
    pub port: u16,
    pub user: String,
    pub version: String,
}