use super::{bind_addr, paths_daemon_log, spawn_detached, stop_existing_for_restart};
pub fn restart(json: bool, quiet: bool) -> anyhow::Result<()> {
let old_pid = stop_existing_for_restart(json || quiet)?;
let new_pid = spawn_detached()?;
if json {
println!("{}", restart_json(old_pid, new_pid));
} else {
println!("{}", restart_rotation_line(old_pid, new_pid));
if !quiet {
report_endpoints();
}
}
Ok(())
}
pub(crate) fn restart_rotation_line(old: Option<u32>, new: u32) -> String {
let old = old.map_or_else(|| "none".to_string(), |pid| pid.to_string());
format!("restarted: pid {old} -> {new}")
}
pub(crate) fn restart_json(old: Option<u32>, new: u32) -> String {
serde_json::json!({
"old": old,
"new": new,
"address": bind_addr(),
})
.to_string()
}
pub(crate) fn start_detached_and_report(verb: &str) -> anyhow::Result<()> {
let pid = spawn_detached()?;
println!(
"moadim {verb} in the background (pid {pid}) at http://{}",
bind_addr()
);
report_endpoints();
maybe_hint_install();
Ok(())
}
fn report_endpoints() {
println!(" UI http://{}", bind_addr());
println!(" stop moadim stop (or use the STOP button in the UI)");
println!(" logs {}", paths_daemon_log());
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) fn maybe_hint_install() {
let marker = crate::paths::install_prompt_marker_path();
let installed = crate::service::is_installed().unwrap_or(true);
if !should_hint_install(marker.exists(), installed) {
return;
}
println!(
"moadim is not installed as a system service, so it won't restart on crash or survive a \
reboot."
);
println!(" run `moadim install` to fix that (this hint won't show again)");
if let Some(parent) = marker.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(&marker, "");
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn maybe_hint_install() {}
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) const fn should_hint_install(marker_exists: bool, installed: bool) -> bool {
!marker_exists && !installed
}