summaryrefslogtreecommitdiff
path: root/init/src/host/timezone.rs
diff options
context:
space:
mode:
Diffstat (limited to 'init/src/host/timezone.rs')
-rw-r--r--init/src/host/timezone.rs67
1 files changed, 67 insertions, 0 deletions
diff --git a/init/src/host/timezone.rs b/init/src/host/timezone.rs
new file mode 100644
index 0000000..2da9e85
--- /dev/null
+++ b/init/src/host/timezone.rs
@@ -0,0 +1,67 @@
+use crate::log::*;
+use std::fs;
+
+pub fn set_timezone(timezone: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
+ let tz = match timezone {
+ Some(tz) => tz,
+ None => {
+ if let Ok(content) = fs::read_to_string("/etc/timezone") {
+ content.trim().to_string()
+ } else if let Ok(link_info) = fs::read_link("/etc/localtime") {
+ let path_str = link_info.to_string_lossy();
+ if path_str.starts_with("/usr/share/zoneinfo/") {
+ let tz_part = path_str.strip_prefix("/usr/share/zoneinfo/").unwrap_or("");
+ tz_part.to_string()
+ } else {
+ "UTC".to_string()
+ }
+ } else {
+ "UTC".to_string()
+ }
+ }
+ };
+
+ let tz_file_path = format!("/usr/share/zoneinfo/{}", tz);
+
+ if !std::path::Path::new(&tz_file_path).exists() {
+ log_warning(&format!(
+ "Timezone '{}' not found in zoneinfo, using UTC",
+ tz
+ ));
+ let result = set_system_timezone_to_utc();
+ if let Err(e) = result {
+ log_critical_error(&format!("Failed to set timezone to UTC: {}", e));
+ return Err(e);
+ }
+ return Ok(());
+ }
+
+ if std::path::Path::new("/etc/localtime").exists() {
+ std::fs::remove_file("/etc/localtime")?;
+ }
+
+ std::os::unix::fs::symlink(&tz_file_path, "/etc/localtime")?;
+
+ log_success(&format!("Timezone set to {}", tz));
+
+ unsafe {
+ std::env::set_var("TZ", &tz);
+ }
+
+ Ok(())
+}
+
+fn set_system_timezone_to_utc() -> Result<(), Box<dyn std::error::Error>> {
+ let utc_tz_path = "/usr/share/zoneinfo/Etc/UTC";
+ if std::path::Path::new("/etc/localtime").exists() {
+ std::fs::remove_file("/etc/localtime")?;
+ }
+
+ std::os::unix::fs::symlink(utc_tz_path, "/etc/localtime")?;
+ log_success("Timezone set to UTC");
+ unsafe {
+ std::env::set_var("TZ", "UTC");
+ }
+
+ Ok(())
+}