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
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃                                                                           ┃
// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

use std::{net, path};

// --------- //
// Structure //
// --------- //

#[derive(Debug)]
#[derive(serde::Deserialize)]
pub struct Settings {
	/// Nom d'hôte / IP de connexion du serveur.
	pub host: net::IpAddr,
	/// Port de connexion du serveur.
	pub port: u16,
	/// Paramètres TLS.
	pub tls: Option<SettingsTLS>,

	#[serde(default)]
	pub static_resources: Vec<SettingsStaticResource>,
}

#[derive(Debug)]
#[derive(serde::Deserialize)]
pub struct SettingsTLS {
	/// Certificat TLS.
	pub cert: path::PathBuf,
	/// Clé TSL.
	pub key: path::PathBuf,
}

#[derive(Debug)]
#[derive(Clone)]
#[derive(serde::Deserialize)]
pub struct SettingsStaticResource {
	/// Un chemin d'URL accessible aux utilisateurs.
	pub url_path: String,
	/// Répertoire des ressources statiques.
	pub dir_path: path::PathBuf,
}

// -------------- //
// Implémentation //
// -------------- //

impl Settings {
	pub fn fetch_or_default(
		config_dir: &impl AsRef<path::Path>,
		file_extension: &crate::application::SettingsLoaderExtension,
	) -> Self {
		lexa_fs::load(config_dir, "server", file_extension).unwrap_or_else(
			|err| {
				let default_settings = Default::default();
				log::error!(
					"Attempt to retrieve server configuration file failed.
					 File: `{}.{}`
					 Error: `{}`",
					config_dir.as_ref().join("server").display(),
					&file_extension,
					err
				);
				log::warn!(
					"The default server configuration parameters returned \
					 are: {:#?}",
					&default_settings
				);
				default_settings
			},
		)
	}
}

// -------------- //
// Implémentation // -> Interface
// -------------- //

impl Default for Settings {
	fn default() -> Self {
		Self {
			host: net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
			port: 80,
			tls: Default::default(),
			static_resources: Default::default(),
		}
	}
}