use std::{path::PathBuf, process::Command}; use yaml_rust2::YamlLoader; use anyhow::{Result, anyhow}; use ini::Ini; use crate::model::profile::{Network, NetworkType}; impl Network { pub fn load_from_ini(&mut self, ini: &Ini) -> Result<()> { log::debug!("loading network"); if let Some(s) = ini.section(Some("dns")) { if let Some(default) = s.get("default") { if default.starts_with("192.") || default.starts_with("127.") { self.network_type = NetworkType::Artemis; } else { self.network_type = NetworkType::Remote; self.remote_address = default.to_owned(); } } } if let Some(s) = ini.section(Some("netenv")) { s.get("addrSuffix").map(|v| self.suffix = v.parse::().ok() ); } if let Some(s) = ini.section(Some("keychip")) { s.get("subnet").map(|v| self.subnet = v.to_owned()); s.get("id").map(|v| self.keychip = v.to_owned()); } Ok(()) } pub fn line_up(&self, ini: &mut Ini) -> Result<()> { log::debug!("begin line-up: network"); ini.with_section(Some("dns")).set("default", &self.remote_address); let mut section_netenv = ini.with_section(Some("netenv")); section_netenv.set("enable", "1"); if let Some(suffix) = self.suffix { section_netenv.set("addrSuffix", suffix.to_string()); } let mut section_keychip = ini.with_section(Some("keychip")); if self.subnet.len() > 0 { section_keychip.set("subnet", &self.subnet); } if self.network_type == NetworkType::Artemis { let network_path = PathBuf::from(&self.local_path); let artemis_dir = network_path.parent() .ok_or_else(|| anyhow!("Invalid ARTEMiS path {:?}", &self.local_path))?; let cfg_path = artemis_dir.join("config").join("core.yaml"); let cfg = std::fs::read_to_string(&cfg_path) .map_err(|e| anyhow!("Unable to open core.yaml: {}", e))?; let cfg = YamlLoader::load_from_str(&cfg) .map_err(|e| anyhow!("Unable to read core.yaml: {}", e))?; let cfg = &cfg[0]; log::debug!("{:?}", cfg); let hostname = &cfg["server"]["hostname"]; let hostname = hostname.clone().into_string(); if let Some(hostname) = hostname { ini.with_section(Some("dns")).set("default", hostname); let mut cmd: Command; if cfg!(target_os = "windows") { cmd = Command::new("cmd.exe"); cmd.arg("/C"); // if self.local_console == true { cmd.arg("start"); cmd.arg("/min"); // } } else { cmd = Command::new("sh"); } cmd.arg("python"); cmd.arg(&self.local_path); cmd.current_dir(artemis_dir); cmd.spawn() .map_err(|e| anyhow!("unable to spawn artemis: {}", e))?; } else { log::warn!("unable to parse the artemis hostname"); } } else if self.keychip.len() > 0 { section_keychip.set("id", &self.keychip); } log::debug!("end line-up: network"); Ok(()) } }