summaryrefslogtreecommitdiff
path: root/init/src/host/locale.rs
blob: 6dc43b20387434317b25187cdd12dd1d4ade8f07 (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
use crate::host::timezone::set_timezone;
use crate::log::{log_success, log_warning};
use std::fs;
use std::io::Write;
use std::process::Command;

pub fn set_locale(locale: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
    let loc = match locale {
        Some(l) => l,
        None => {
            if let Ok(content) = fs::read_to_string("/etc/default/locale") {
                for line in content.lines() {
                    if line.starts_with("LANG=") {
                        let parts: Vec<&str> = line.split('=').collect();
                        if parts.len() >= 2 {
                            let lang_val = parts[1];
                            let clean_lang = lang_val.trim_matches('"').trim_matches('\'');
                            if !clean_lang.is_empty() {
                                return set_system_locale(clean_lang);
                            }
                        }
                    }
                }
            }

            if let Ok(lang_env) = std::env::var("LANG") 
                && !lang_env.is_empty() {
                    return set_system_locale(&lang_env);
                
            }
            if locale_exists("C.UTF-8") {
                "C.UTF-8".to_string()
            } else if locale_exists("en_US.UTF-8") {
                "en_US.UTF-8".to_string()
            } else {
                "C".to_string()
            }
        }
    };

    set_system_locale(&loc)
}
fn set_system_locale(locale: &str) -> Result<(), Box<dyn std::error::Error>> {
    if !locale_exists(locale) {
        log_warning(&format!(
            "Locale '{}' not found in system, trying alternatives",
            locale
        ));

        let variants = vec![
            format!("{}.UTF-8", locale),
            locale.replace('_', "-"), // Sometimes locales are in form en-US
            format!("{}.UTF-8", locale.replace('_', "-")),
        ];

        for variant in variants {
            if locale_exists(&variant) {
                log_success(&format!("Using alternative locale: {}", variant));
                return set_system_locale_impl(&variant);
            }
        }

        log_warning("No matching locale found, using C.UTF-8 as fallback");
        return set_system_locale_impl("C.UTF-8");
    }

    set_system_locale_impl(locale)
}

fn set_system_locale_impl(locale: &str) -> Result<(), Box<dyn std::error::Error>> {
    unsafe {
        std::env::set_var("LANG", locale);
        std::env::set_var("LC_ALL", locale);

        std::env::set_var("LC_CTYPE", locale);
        std::env::set_var("LC_NUMERIC", locale);
        std::env::set_var("LC_TIME", locale);
        std::env::set_var("LC_COLLATE", locale);
        std::env::set_var("LC_MONETARY", locale);
        std::env::set_var("LC_MESSAGES", locale);
        std::env::set_var("LC_PAPER", locale);
        std::env::set_var("LC_NAME", locale);
        std::env::set_var("LC_ADDRESS", locale);
        std::env::set_var("LC_TELEPHONE", locale);
        std::env::set_var("LC_MEASUREMENT", locale);
        std::env::set_var("LC_IDENTIFICATION", locale);
    }

    if let Ok(mut file) = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open("/etc/default/locale")
    {
        writeln!(file, "# Generated by Vigil init system")?;
        writeln!(file, "LANG=\"{}\"", locale)?;
        writeln!(file, "LC_ALL=\"{}\"", locale)?;
        file.flush()?;
    } else {
        log_warning("Could not write to /etc/default/locale, locale settings may not persist");
    }

    log_success(&format!("Locale set to {}", locale));
    Ok(())
}

fn locale_exists(locale: &str) -> bool {
    if let Ok(output) = Command::new("locale").arg("-a").output() {
        let output_str = String::from_utf8_lossy(&output.stdout);
        output_str.lines().any(|line| line.trim() == locale)
    } else {
        let locale_archive_path = "/usr/lib/locale/locale-archive".to_string();
        let locale_dir_path = "/usr/lib/locale/".to_string();

        std::path::Path::new(&locale_archive_path).exists()
            || std::path::Path::new(&locale_dir_path).exists()
    }
}

pub fn set_system_localization(
    timezone: Option<String>,
    locale: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Err(e) = set_timezone(timezone) {
        log_warning(&format!("Failed to set timezone: {}", e));
    }

    if let Err(e) = set_locale(locale) {
        log_warning(&format!("Failed to set locale: {}", e));
    }

    Ok(())
}