smirrors 0.1.0

Automatic mirror list updater for Linux distributions
Documentation
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Distribution detection module
//!
//! Provides comprehensive Linux distribution detection using multiple methods:
//! - /etc/os-release (systemd standard)
//! - /etc/lsb-release (LSB standard)
//! - Distribution-specific files
//! - Fallback detection methods

use super::Distro;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use tracing::{debug, warn};

/// Distribution detector
pub struct DistroDetector;

impl DistroDetector {
    /// Detect the current Linux distribution
    ///
    /// Uses multiple detection methods in order of preference:
    /// 1. /etc/os-release (most reliable, systemd standard)
    /// 2. /etc/lsb-release (LSB standard)
    /// 3. Distribution-specific files
    /// 4. Package manager detection (fallback)
    pub fn detect() -> Result<Distro> {
        // Try os-release first (most reliable)
        if let Ok(distro) = Self::detect_from_os_release() {
            debug!("Detected distribution from os-release: {:?}", distro);
            return Ok(distro);
        }

        // Try lsb-release
        if let Ok(distro) = Self::detect_from_lsb_release() {
            debug!("Detected distribution from lsb-release: {:?}", distro);
            return Ok(distro);
        }

        // Try distro-specific files
        if let Ok(distro) = Self::detect_from_specific_files() {
            debug!("Detected distribution from specific files: {:?}", distro);
            return Ok(distro);
        }

        // Try package manager detection as fallback
        if let Ok(distro) = Self::detect_from_package_manager() {
            debug!("Detected distribution from package manager: {:?}", distro);
            return Ok(distro);
        }

        warn!("Could not detect distribution, using Unknown");
        Ok(Distro::Unknown)
    }

    /// Detect distribution from /etc/os-release
    fn detect_from_os_release() -> Result<Distro> {
        let content = fs::read_to_string("/etc/os-release")
            .context("Failed to read /etc/os-release")?;

        let vars = Self::parse_shell_vars(&content);

        // Get ID and ID_LIKE for fallback
        let id = vars.get("ID").map(|s| s.as_str()).unwrap_or("");
        let id_like = vars.get("ID_LIKE").map(|s| s.as_str()).unwrap_or("");

        debug!("os-release ID: {}, ID_LIKE: {}", id, id_like);

        // Check ID first
        let distro = Self::map_id_to_distro(id);
        if distro != Distro::Unknown {
            return Ok(distro);
        }

        // Check ID_LIKE (space-separated list)
        for like_id in id_like.split_whitespace() {
            let distro = Self::map_id_to_distro(like_id);
            if distro != Distro::Unknown {
                return Ok(distro);
            }
        }

        anyhow::bail!("Unknown distribution in os-release: {}", id)
    }

    /// Detect distribution from /etc/lsb-release
    fn detect_from_lsb_release() -> Result<Distro> {
        let content = fs::read_to_string("/etc/lsb-release")
            .context("Failed to read /etc/lsb-release")?;

        let vars = Self::parse_shell_vars(&content);

        let distro_id = vars
            .get("DISTRIB_ID")
            .map(|s| s.to_lowercase())
            .unwrap_or_default();

        debug!("lsb-release DISTRIB_ID: {}", distro_id);

        let distro = Self::map_id_to_distro(&distro_id);
        if distro != Distro::Unknown {
            Ok(distro)
        } else {
            anyhow::bail!("Unknown distribution in lsb-release: {}", distro_id)
        }
    }

    /// Detect distribution from distribution-specific files
    fn detect_from_specific_files() -> Result<Distro> {
        // Check for distribution-specific version files
        if Path::new("/etc/debian_version").exists() {
            // Could be Debian or Ubuntu
            if Path::new("/etc/lsb-release").exists() {
                let content = fs::read_to_string("/etc/lsb-release").ok();
                if let Some(content) = content {
                    if content.contains("Ubuntu") {
                        return Ok(Distro::Ubuntu);
                    }
                }
            }
            return Ok(Distro::Debian);
        }

        if Path::new("/etc/fedora-release").exists() {
            return Ok(Distro::Fedora);
        }

        if Path::new("/etc/redhat-release").exists() {
            let content = fs::read_to_string("/etc/redhat-release").ok();
            if let Some(content) = content {
                let lower = content.to_lowercase();
                if lower.contains("fedora") {
                    return Ok(Distro::Fedora);
                } else if lower.contains("red hat") || lower.contains("rhel") {
                    return Ok(Distro::RHEL);
                }
            }
            return Ok(Distro::RHEL);
        }

        if Path::new("/etc/arch-release").exists() {
            return Ok(Distro::Arch);
        }

        if Path::new("/etc/manjaro-release").exists() {
            return Ok(Distro::Manjaro);
        }

        if Path::new("/etc/SuSE-release").exists() || Path::new("/etc/SUSE-brand").exists() {
            return Ok(Distro::OpenSUSE);
        }

        anyhow::bail!("No distribution-specific files found")
    }

    /// Detect distribution from available package managers (fallback)
    fn detect_from_package_manager() -> Result<Distro> {
        // Check for package manager binaries
        if Self::command_exists("apt") || Self::command_exists("apt-get") {
            // Could be Debian or Ubuntu, default to Debian
            return Ok(Distro::Debian);
        }

        if Self::command_exists("dnf") {
            return Ok(Distro::Fedora);
        }

        if Self::command_exists("yum") {
            return Ok(Distro::RHEL);
        }

        if Self::command_exists("pacman") {
            return Ok(Distro::Arch);
        }

        if Self::command_exists("zypper") {
            return Ok(Distro::OpenSUSE);
        }

        anyhow::bail!("No known package manager found")
    }

    /// Map distribution ID to Distro enum
    fn map_id_to_distro(id: &str) -> Distro {
        let id_lower = id.to_lowercase();

        match id_lower.as_str() {
            "debian" => Distro::Debian,
            "ubuntu" => Distro::Ubuntu,
            "fedora" => Distro::Fedora,
            "rhel" | "redhat" | "red hat" => Distro::RHEL,
            "centos" => Distro::RHEL, // CentOS uses RHEL-compatible repos
            "rocky" | "rockylinux" => Distro::RHEL, // Rocky Linux
            "alma" | "almalinux" => Distro::RHEL, // AlmaLinux
            "arch" => Distro::Arch,
            "manjaro" => Distro::Manjaro,
            "opensuse" | "opensuse-leap" | "opensuse-tumbleweed" | "suse" => Distro::OpenSUSE,
            "linuxmint" | "mint" => Distro::Ubuntu, // Mint is Ubuntu-based
            "pop" | "pop!_os" => Distro::Ubuntu, // Pop!_OS is Ubuntu-based
            "elementary" | "elementaryos" => Distro::Ubuntu, // Elementary is Ubuntu-based
            "zorin" | "zorinos" => Distro::Ubuntu, // Zorin is Ubuntu-based
            "kali" => Distro::Debian, // Kali is Debian-based
            "parrot" => Distro::Debian, // Parrot is Debian-based
            "raspbian" => Distro::Debian, // Raspbian is Debian-based
            "endeavouros" | "endeavour" => Distro::Arch, // EndeavourOS is Arch-based
            "garuda" | "garudalinux" => Distro::Arch, // Garuda is Arch-based
            "artix" => Distro::Arch, // Artix is Arch-based
            _ => Distro::Unknown,
        }
    }

    /// Parse shell-style variable assignments (KEY=VALUE or KEY="VALUE")
    fn parse_shell_vars(content: &str) -> HashMap<String, String> {
        let mut vars = HashMap::new();

        for line in content.lines() {
            let line = line.trim();

            // Skip comments and empty lines
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse KEY=VALUE
            if let Some(eq_pos) = line.find('=') {
                let key = line[..eq_pos].trim().to_string();
                let value = line[eq_pos + 1..].trim();

                // Remove quotes if present
                let value = if (value.starts_with('"') && value.ends_with('"'))
                    || (value.starts_with('\'') && value.ends_with('\''))
                {
                    value[1..value.len() - 1].to_string()
                } else {
                    value.to_string()
                };

                vars.insert(key, value);
            }
        }

        vars
    }

    /// Check if a command exists in PATH
    fn command_exists(cmd: &str) -> bool {
        std::process::Command::new("which")
            .arg(cmd)
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    }

    /// Check if running in WSL (Windows Subsystem for Linux)
    pub fn is_wsl() -> bool {
        // Check for WSL-specific files
        if Path::new("/proc/sys/fs/binfmt_misc/WSLInterop").exists() {
            return true;
        }

        // Check kernel version for WSL signature
        if let Ok(content) = fs::read_to_string("/proc/version") {
            if content.to_lowercase().contains("microsoft") {
                return true;
            }
        }

        false
    }

    /// Check if running in a container
    pub fn is_container() -> bool {
        // Check for Docker
        if Path::new("/.dockerenv").exists() {
            return true;
        }

        // Check for container environments in cgroup
        if let Ok(content) = fs::read_to_string("/proc/1/cgroup") {
            if content.contains("docker") || content.contains("lxc") || content.contains("kubepods")
            {
                return true;
            }
        }

        // Check for systemd container detection
        if let Ok(content) = fs::read_to_string("/run/systemd/container") {
            if !content.trim().is_empty() {
                return true;
            }
        }

        false
    }

    /// Get detailed distribution information
    pub fn get_info() -> Result<DistroInfo> {
        let distro = Self::detect()?;
        let content = fs::read_to_string("/etc/os-release")
            .or_else(|_| fs::read_to_string("/etc/lsb-release"))
            .context("Failed to read release file")?;

        let vars = Self::parse_shell_vars(&content);

        Ok(DistroInfo {
            distro,
            name: vars
                .get("NAME")
                .or_else(|| vars.get("DISTRIB_ID"))
                .cloned()
                .unwrap_or_else(|| distro.as_str().to_string()),
            version: vars
                .get("VERSION_ID")
                .or_else(|| vars.get("DISTRIB_RELEASE"))
                .cloned(),
            codename: vars
                .get("VERSION_CODENAME")
                .or_else(|| vars.get("DISTRIB_CODENAME"))
                .cloned(),
            pretty_name: vars.get("PRETTY_NAME").cloned(),
            is_wsl: Self::is_wsl(),
            is_container: Self::is_container(),
        })
    }
}

/// Detailed distribution information
#[derive(Debug, Clone)]
pub struct DistroInfo {
    pub distro: Distro,
    pub name: String,
    pub version: Option<String>,
    pub codename: Option<String>,
    pub pretty_name: Option<String>,
    pub is_wsl: bool,
    pub is_container: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_shell_vars() {
        let content = r#"
# Comment
NAME="Ubuntu"
ID=ubuntu
VERSION_ID="22.04"
SIMPLE=value
EMPTY=
"#;

        let vars = DistroDetector::parse_shell_vars(content);

        assert_eq!(vars.get("NAME"), Some(&"Ubuntu".to_string()));
        assert_eq!(vars.get("ID"), Some(&"ubuntu".to_string()));
        assert_eq!(vars.get("VERSION_ID"), Some(&"22.04".to_string()));
        assert_eq!(vars.get("SIMPLE"), Some(&"value".to_string()));
        assert_eq!(vars.get("EMPTY"), Some(&"".to_string()));
    }

    #[test]
    fn test_map_id_to_distro() {
        assert_eq!(DistroDetector::map_id_to_distro("ubuntu"), Distro::Ubuntu);
        assert_eq!(DistroDetector::map_id_to_distro("debian"), Distro::Debian);
        assert_eq!(DistroDetector::map_id_to_distro("fedora"), Distro::Fedora);
        assert_eq!(DistroDetector::map_id_to_distro("arch"), Distro::Arch);
        assert_eq!(
            DistroDetector::map_id_to_distro("manjaro"),
            Distro::Manjaro
        );
        assert_eq!(
            DistroDetector::map_id_to_distro("opensuse"),
            Distro::OpenSUSE
        );
        assert_eq!(DistroDetector::map_id_to_distro("rhel"), Distro::RHEL);
        assert_eq!(DistroDetector::map_id_to_distro("centos"), Distro::RHEL);
    }

    #[test]
    fn test_map_derivatives() {
        // Ubuntu derivatives
        assert_eq!(DistroDetector::map_id_to_distro("mint"), Distro::Ubuntu);
        assert_eq!(DistroDetector::map_id_to_distro("pop"), Distro::Ubuntu);

        // Debian derivatives
        assert_eq!(DistroDetector::map_id_to_distro("kali"), Distro::Debian);
        assert_eq!(DistroDetector::map_id_to_distro("parrot"), Distro::Debian);

        // Arch derivatives
        assert_eq!(
            DistroDetector::map_id_to_distro("endeavour"),
            Distro::Arch
        );
        assert_eq!(DistroDetector::map_id_to_distro("garuda"), Distro::Arch);

        // RHEL derivatives
        assert_eq!(DistroDetector::map_id_to_distro("rocky"), Distro::RHEL);
        assert_eq!(DistroDetector::map_id_to_distro("alma"), Distro::RHEL);
    }

    #[test]
    fn test_unknown_distro() {
        assert_eq!(
            DistroDetector::map_id_to_distro("unknown_distro"),
            Distro::Unknown
        );
    }
}