use std::ffi::OsString;
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;
use anyhow::{Context, Result};
use crate::store::Home;
static PREFIX: OnceLock<Vec<OsString>> = OnceLock::new();
pub fn handle_relaunch(prefix: &[&str]) {
let _ = PREFIX.set(prefix.iter().map(OsString::from).collect());
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
let Some(rest) = args.strip_prefix(self::prefix()) else { return };
let words: Vec<&str> = rest.iter().map(|word| word.to_str().unwrap_or("")).collect();
let result = match words.as_slice() {
["daemon"] => Home::locate().and_then(|home| crate::ops::serve_mounts(home, false)),
["daemon", "--serve"] => Home::locate().and_then(|home| crate::ops::serve_mounts(home, true)),
["shell-exec", "--", _, ..] => crate::shell::exec_in_new_session(&rest[2..]),
["git-fsmonitor", version, ..] => Home::locate().and_then(|home| crate::ops::git_fsmonitor(&home, version)),
_ => return,
};
match result {
Ok(()) => std::process::exit(0),
Err(err) => {
eprintln!("sandfs: {err:#}");
std::process::exit(1)
}
}
}
pub(crate) fn prefix() -> &'static [OsString] {
PREFIX.get().map_or(&[], Vec::as_slice)
}
pub(crate) fn program() -> Result<PathBuf> {
let exe = std::env::current_exe().context("finding this program")?;
match exe.to_str().and_then(|exe| exe.strip_suffix(" (deleted)")) {
Some(exe) => Ok(PathBuf::from(exe)),
None => Ok(exe),
}
}
pub(crate) fn command() -> Result<Command> {
let mut command = Command::new(std::env::current_exe().context("finding this program")?);
command.args(prefix());
Ok(command)
}