summaryrefslogtreecommitdiff
path: root/src/config.rs
blob: ff83f01a30cc23b23b1b764e1036e51c02aca603 (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
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use colored::Colorize;

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RepositoryConfig {
    pub url: String,
    #[serde(default)]
    pub urlrepo: Option<String>,
    #[serde(default)]
    pub mirror: Option<String>,
    #[serde(default = "default_gpg_support")]
    pub gpg_support: bool,
    #[serde(default)]
    pub gpg_key: Option<String>,
}

fn default_gpg_support() -> bool { true }

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct GlobalConfig {
    #[serde(default = "default_ignore_speed")]
    pub ignore_speed: bool,
    #[serde(default = "default_strict_gpg")]
    pub strict_gpg: bool,
    #[serde(default)]
    pub allow_external_binaries: bool,
    #[serde(default = "default_parallel_downloads")]
    pub parallel_downloads: usize,
    #[serde(default = "default_arch")]
    pub arch: String,
    #[serde(default = "default_libc")]
    pub libc: String,
}

impl Default for GlobalConfig {
    fn default() -> Self {
        Self {
            ignore_speed: false,
            strict_gpg: false,
            allow_external_binaries: false,
            parallel_downloads: default_parallel_downloads(),
            arch: default_arch(),
            libc: default_libc(),
        }
    }
}

fn default_ignore_speed() -> bool { false }
fn default_strict_gpg() -> bool { false }
fn default_parallel_downloads() -> usize { 4 }
fn default_arch() -> String { std::env::consts::ARCH.to_string() }
fn default_libc() -> String { "glibc".to_string() }

#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct SystemProfile {
    #[serde(rename = "init-system", default)]
    pub init_system: Option<String>,
    #[serde(default)]
    pub libc: Option<String>,
    #[serde(rename = "core-utils", default)]
    pub core_utils: Option<String>,
    #[serde(default)]
    pub sh: Vec<String>,
    #[serde(default)]
    pub su: Vec<String>,
    #[serde(default)]
    pub udev: Option<String>,
    #[serde(rename = "active-group", default)]
    pub active_group: Option<String>,
}

impl SystemProfile {
    pub fn group_name(&self) -> Option<String> {
        if let Some(g) = &self.active_group {
            return Some(g.clone());
        }
        let init = self.init_system.as_deref()?;
        let libc = self.libc.as_deref()?;
        let utils = self.core_utils.as_deref()?;
        let sh = self.sh.first().map(|s| s.as_str())?;
        let su = self.su.first().map(|s| s.as_str())?;
        let udev = self.udev.as_deref()?;
        Some(format!("{}-{}-{}-{}-{}-{}-min", init, libc, utils, sh, su, udev))
    }

    pub fn set_single_role(&mut self, role: &str, pkg: &str) {
        match role {
            "init-system" => self.init_system = Some(pkg.to_string()),
            "libc"        => self.libc = Some(pkg.to_string()),
            "core-utils"  => self.core_utils = Some(pkg.to_string()),
            "udev"        => self.udev = Some(pkg.to_string()),
            _ => {}
        }
    }

    pub fn replace_in_list_role(&mut self, role: &str, old_pkg: &str, new_pkg: &str) {
        let list = match role {
            "sh" => &mut self.sh,
            "su" => &mut self.su,
            _ => return,
        };
        if let Some(pos) = list.iter().position(|p| p == old_pkg) {
            list[pos] = new_pkg.to_string();
        } else {
            list.push(new_pkg.to_string());
        }
    }
    #[allow(dead_code)]
    pub fn remove_from_list_role(&mut self, role: &str, pkg: &str) {
        let list = match role {
            "sh" => &mut self.sh,
            "su" => &mut self.su,
            _ => return,
        };
        list.retain(|p| p != pkg);
    }
}

#[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct Config {
    #[serde(default)]
    pub global: GlobalConfig,
    #[serde(default)]
    pub repositories: HashMap<String, RepositoryConfig>,
    #[serde(default)]
    pub profile: SystemProfile,
}

impl Config {
    pub fn load() -> Self {
        let path = Path::new("/etc/ror/ror.conf");
        if path.exists() {
            let content = fs::read_to_string(path).unwrap_or_default();
            Self::from_ini(&content).unwrap_or_else(|e| {
                eprintln!(
                    "{} Failed to parse config: {}, using defaults",
                    "[ror]".red().bold(),
                    e
                );
                Config::default()
            })
        } else {
            Config::default()
        }
    }

    pub fn save(&self) -> std::io::Result<()> {
        let path = Path::new("/etc/ror/ror.conf");
        let ini = self.to_ini().map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, ini)
    }

    pub fn to_ini(&self) -> Result<String, config::ConfigError> {
        let mut lines = vec!["[global]".to_string()];
        lines.push(format!("ignore_speed = {}", self.global.ignore_speed));
        lines.push(format!("strict_gpg = {}", self.global.strict_gpg));
        lines.push(format!("parallel_downloads = {}", self.global.parallel_downloads));
        lines.push(format!("arch = {}", self.global.arch));
        lines.push(format!("libc = {}", self.global.libc));
        lines.push(String::new());

        let p = &self.profile;
        let has_profile = p.init_system.is_some() || p.libc.is_some()
            || p.core_utils.is_some() || !p.sh.is_empty()
            || !p.su.is_empty() || p.udev.is_some() || p.active_group.is_some();

        if has_profile {
            lines.push("[profile]".to_string());
            if let Some(v) = &p.active_group  { lines.push(format!("active-group = {}", v)); }
            if let Some(v) = &p.init_system   { lines.push(format!("init-system = {}", v)); }
            if let Some(v) = &p.libc          { lines.push(format!("libc = {}", v)); }
            if let Some(v) = &p.core_utils    { lines.push(format!("core-utils = {}", v)); }
            if !p.sh.is_empty()               { lines.push(format!("sh = {}", p.sh.join(","))); }
            if !p.su.is_empty()               { lines.push(format!("su = {}", p.su.join(","))); }
            if let Some(v) = &p.udev          { lines.push(format!("udev = {}", v)); }
            lines.push(String::new());
        }

        for (name, repo) in &self.repositories {
            lines.push(format!("[repositories.{}]", name));
            lines.push(format!("url = \"{}\"", repo.url));
            if let Some(v) = &repo.urlrepo {
                lines.push(format!("urlrepo = \"{}\"", v));
            }
            if let Some(m) = &repo.mirror {
                lines.push(format!("mirror = \"{}\"", m));
            }
            lines.push(format!("gpg_support = {}", repo.gpg_support));
            if let Some(k) = &repo.gpg_key {
                lines.push(format!("gpg_key = \"{}\"", k));
            }
            lines.push(String::new());
        }
        Ok(lines.join("\n"))
    }

    pub fn from_ini(ini: &str) -> Result<Self, config::ConfigError> {
        let builder = config::Config::builder()
            .add_source(config::File::from_str(ini, config::FileFormat::Ini));
        let cfg = builder.build()?;
        cfg.try_deserialize()
    }

    pub fn create_default_config(path: &Path) -> std::io::Result<()> {
        let ini = concat!(
            "[global]\n",
            "ignore_speed = false\n",
            "strict_gpg = false\n",
            "parallel_downloads = 4\n",
            "arch = x86_64\n",
            "libc = glibc\n",
            "\n",
            "[repositories.rorkos]\n",
            "url = \"https://github.com/RorkOS/RorkOS_package\"\n",
            "urlrepo = \"https://github.com/RorkOS/RorkOS_packages_bin/releases/download/latest/\"\n",
            "mirror = \"https://github.com/rork-os/RorkOS_package\"\n",
            "gpg_support = true\n",
            "gpg_key = \"rorka.pub\"\n",
        );
        fs::create_dir_all(path.parent().unwrap())?;
        fs::write(path, ini)
    }
}