summaryrefslogtreecommitdiff
path: root/src/cfg/config.rs
blob: eaa703c0c638a7fa02b0fd4d1f1af5ef52b7d02a (plain)
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
use serde::{Deserialize, Serialize, de::Error as DeError};
use std::fs;
use toml;

#[derive(Deserialize, Debug, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Loglevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

/// `mesk.toml` configuration fields here
#[derive(Deserialize, Debug, Serialize, Clone)]
pub struct RouterConfig {
    #[serde(default = "default_integrated_router")]
    pub integrated_router: bool,
    #[serde(default = "default_router_storage")]
    pub storage_path: String,
    #[serde(default = "default_http_proxy_port")]
    pub http_proxy_port: u16,
    #[serde(default = "default_socks_proxy_port")]
    pub socks_proxy_port: u16,
    #[serde(default = "default_auto_update")]
    pub auto_update: bool,
}

fn default_integrated_router() -> bool {
    false
}
fn default_router_storage() -> String {
    "/var/lib/mesk/router/".to_string()
}
fn default_http_proxy_port() -> u16 {
    4445
}
fn default_socks_proxy_port() -> u16 {
    4446
}
fn default_auto_update() -> bool {
    true
}

#[derive(Deserialize, Debug, Serialize, Clone)]
pub struct Config {
    pub repo: Repo,
    pub log: Log,
    pub paths: Paths,
    #[serde(default = "RouterConfig::default")]
    pub router: RouterConfig,
}

impl Default for RouterConfig {
    fn default() -> Self {
        Self {
            integrated_router: default_integrated_router(),
            storage_path: default_router_storage(),
            http_proxy_port: default_http_proxy_port(),
            socks_proxy_port: default_socks_proxy_port(),
            auto_update: default_auto_update(),
        }
    }
}

#[derive(Deserialize, Debug, Serialize, Clone)]
pub struct Log {
    #[serde(rename = "log_file")]
    pub log_file: String,
    #[serde(rename = "log_level")]
    pub log_level: Loglevel,
}

// Rename needed for editing mesk.toml file fields but dont touch code.
#[derive(Deserialize, Debug, Serialize, Clone)]
pub struct Repo {
    #[serde(rename = "repo_url")]
    pub repo_url: String,
    #[serde(rename = "auto_update")]
    pub auto_update: bool,
    #[serde(rename = "destination")]
    pub destination: (String, String),
    #[serde(rename = "repo_http_url")]
    pub repo_http_url: Option<String>,
    #[serde(rename = "i2p_http_proxy_port")]
    pub i2p_http_proxy_port: u16,
    //    #[serde(rename = "arch")]
    //    pub arch = arch;
}

#[derive(Deserialize, Debug, Serialize, Clone)]
pub struct Paths {
    #[serde(rename = "cache_dir")]
    pub cache_dir: String,
    #[serde(rename = "build_dir")]
    pub build_dir: String,
    pub installed_db: String,
}

impl Config {
    /// Parse configuration and return the Config object.
    ///
    /// This function first tries to read the `MESK_CONFIG_TOML` environment variable
    /// containing the full TOML configuration. If it is not set, it falls back to
    /// reading the `/etc/mesk/mesk.toml` file.
    pub fn parse() -> Result<Config, toml::de::Error> {
        // Prefer an explicit in-memory config for tests and overrides.
        if let Ok(env_contents) = std::env::var("MESK_CONFIG_TOML") {
            let result: Config = toml::from_str(&env_contents)?;
            return Ok(result);
        }

        // Fallback to the system-wide config file.
        let contents = fs::read_to_string("/etc/mesk/mesk.toml").map_err(|io_err| {
            DeError::custom(format!(
                "Failed to read /etc/mesk/mesk.toml and MESK_CONFIG_TOML is not set: {}",
                io_err
            ))
        })?;

        let result: Config = toml::from_str(&contents)?;
        Ok(result)
    }

    /// Return the default configuration as a toml string.
    ///
    /// This function returns the default configuration as a toml string.
    #[allow(clippy::should_implement_trait)]
    pub fn default() -> Result<String, toml::ser::Error> {
        let default: Config = Config {
            repo: Repo {
                repo_url: format!("https://mesk.anthrill.i2p/repo/{}/", std::env::consts::ARCH),
                auto_update: true,
                destination: (String::from("mesk"), String::from("mesk")),
                repo_http_url: format!(
                    "http://github.com/Anthrill/repo-mirror/{}",
                    std::env::consts::ARCH
                )
                .into(),
                i2p_http_proxy_port: 4444,
                // Its a hurt place, you need to generate destinations by i2pd and paste here (to mesk.toml)
                // Better to leave it empty or set it to (mesk, mesk), now destination conn not implemented
            },
            log: Log {
                log_file: String::from("/var/log/mesk.log"),
                log_level: Loglevel::Info,
            },
            paths: Paths {
                cache_dir: String::from("/var/cache/mesk"),
                build_dir: String::from("/var/lib/mesk"),
                installed_db: String::from("/var/lib/mesk/pkgdb"),
            },
            router: RouterConfig::default(),
        };

        let toml_str = toml::to_string(&default)?;
        Ok(toml_str)
    }

    pub fn generate(
        repo: &Option<String>,
        cachedir: &Option<String>,
        buildir: &Option<String>,
        installed_db: &Option<String>,
    ) -> Result<String, toml::ser::Error> {
        let config = Config {
            repo: Repo {
                repo_url: repo
                    .as_deref()
                    .unwrap_or(&format!(
                        "https://mesk.anthrill.i2p/repo/{}/",
                        std::env::consts::ARCH
                    ))
                    .to_string(),
                auto_update: true,
                destination: (String::from("mesk"), String::from("mesk")),
                repo_http_url: repo.as_ref().map(|r| {
                    r.replace("i2p", "http")
                        .replace("b32.i2p", "github.com/Anthrill/repo-mirror")
                }),
                i2p_http_proxy_port: 4444,
            },
            log: Log {
                log_file: String::from("/var/log/mesk.log"),
                log_level: Loglevel::Info,
            },
            paths: Paths {
                cache_dir: cachedir
                    .clone()
                    .unwrap_or_else(|| "/var/cache/mesk".to_string()),
                build_dir: buildir
                    .clone()
                    .unwrap_or_else(|| "/var/tmp/mesk/build".to_string()),
                installed_db: installed_db
                    .clone()
                    .unwrap_or_else(|| "/var/lib/mesk/installed.db".to_string()),
            },
            router: RouterConfig::default(),
        };
        toml::to_string(&config)
    }
}