use crate::Result;
use crate::dir_context::AipackBaseDir;
use crate::exec::exec_cmd_xelf::support::{get_aip_stable_url, has_aip_in_path};
use crate::hub::{HubEvent, get_hub};
use crate::support::proc::{self, ProcOptions};
use crate::support::webc;
use semver::Version;
use simple_fs::ensure_dir;
const ARCHIVE_NAME: &str = "aip.tar.gz";
pub(super) async fn exec_update_for_nix(remote_version: &Version, is_latest: bool) -> Result<()> {
let hub = get_hub();
hub.publish(format!("Starting update to version {remote_version}...")).await;
let aipack_base_dir = AipackBaseDir::new()?;
let tmp_dir = aipack_base_dir.bin_tmp_dir();
let archive_path = tmp_dir.join(ARCHIVE_NAME);
ensure_dir(&tmp_dir)?;
hub.publish(format!("Using temporary directory: {tmp_dir}")).await;
let proc_opts = ProcOptions::default().with_cwd(&tmp_dir);
hub.publish(format!("Downloading new version ({remote_version})...")).await;
let download_url = if is_latest {
get_aip_stable_url(None)?
} else {
get_aip_stable_url(Some(remote_version))?
};
webc::web_download_to_file(&download_url, &archive_path).await?;
hub.publish(format!("Extracting {ARCHIVE_NAME} in {tmp_dir}...")).await;
proc::proc_exec("tar", &["-xvf", ARCHIVE_NAME], Some(&proc_opts)).await?;
hub.publish("Extraction complete.").await;
let new_aip_exe_path = tmp_dir.join("aip");
hub.publish(format!("Running setup for the new version using {new_aip_exe_path}..."))
.await;
let setup_stdout =
proc::proc_exec_to_output(new_aip_exe_path.as_str(), &["self", "setup"], Some(&proc_opts)).await?;
let setup_str = format!("'aip self setup' executed:\n{setup_stdout}\n");
hub.publish(setup_str).await;
hub.publish(HubEvent::info_short(format!(
"Update successful! New version 'v{remote_version}' installed.\n"
)))
.await;
if !has_aip_in_path() {
hub.publish(HubEvent::info_short(
"It seems you do not have '~/.aipack-base/bin' in path.
Please restart your terminal session or source your shell profile (e.g., `source ~/.bashrc`, `source ~/.zshrc`) for changes to take effect.
"
))
.await;
}
Ok(())
}