use std::{fmt::Display, time::SystemTime};
use e_utils::{chrono, cmd::{Cmd, ExeType}};
pub fn sync_systemtime<T: Into<SystemTime> + Display>(time: T) -> e_utils::AnyResult<()> {
let sys_time: SystemTime = time.into();
#[cfg(target_os = "windows")]
{
let dt = chrono::DateTime::<chrono::Local>::from(sys_time);
let date_str = dt.format("%Y-%m-%d").to_string();
let time_str = dt.format("%H:%M:%S").to_string();
let date_output = Cmd::new("date").set_type(ExeType::Cmd).args(&[date_str]).output()?;
if !date_output.status.success() {
return Err("Failed to set system date on Windows".into());
}
let time_output = Cmd::new("time").set_type(ExeType::Cmd).args(&[time_str]).output()?;
if !time_output.status.success() {
return Err("Failed to set system time on Windows".into());
}
}
#[cfg(target_os = "linux")]
{
let time_str = time.to_string();
let output = Cmd::new("timedatectl")
.args(&["set-time", &time_str])
.output()?;
if !output.status.success() {
return Err("Failed to set system time on Linux".into());
}
}
#[cfg(target_os = "macos")]
{
let time_str = time.to_string();
let output = Cmd::new("date")
.args(&["-u", "-s", &time_str])
.output()?;
if !output.status.success() {
return Err("Failed to set system time on macOS".into());
}
}
Ok(())
}