use crate::ui::Style;
use anyhow::{bail, Result};
use std::path::{Path, PathBuf};
use std::time::Duration;
pub const SERVICE_NAME: &str = "eclipse-gateway.service";
pub(crate) fn unit_path(home: &Path) -> PathBuf {
home.join(".config")
.join("systemd")
.join("user")
.join(SERVICE_NAME)
}
pub(crate) fn units_dir() -> Result<PathBuf> {
let home = std::env::var("HOME").unwrap_or_else(|_| "".into());
if home.is_empty() {
bail!("HOME is not set");
}
Ok(unit_path(Path::new(&home))
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from(&home)))
}
fn unit_text(gateway_bin: &Path, docs: &Path, env: &[(String, String)]) -> String {
let environment: String = env
.iter()
.map(|(key, value)| format!("Environment=\"{key}={value}\"\n"))
.collect();
format!(
"[Unit]\n\
Description=Eclipse gateway — dashboard and API on one pid\n\
Documentation=file:{}\n\
\n\
[Service]\n\
Type=simple\n\
{environment}ExecStart={}\n\
Restart=always\n\
RestartSec=5\n\
\n\
[Install]\n\
WantedBy=default.target\n",
docs.display(),
systemd_word(gateway_bin)
)
}
fn service_env(profile: Option<&str>, config: Option<&Path>) -> Vec<(String, String)> {
let mut env = Vec::new();
if let Some(profile) = profile {
env.push(("ECLIPSE_PROFILE".to_string(), profile.to_string()));
}
if let Some(config) = config {
let absolute = if config.is_absolute() {
config.to_path_buf()
} else {
std::env::current_dir()
.map(|cwd| cwd.join(config))
.unwrap_or_else(|_| config.to_path_buf())
};
env.push(("ECLIPSE_CONFIG".to_string(), absolute.display().to_string()));
}
env
}
pub fn web_bin() -> Result<PathBuf> {
let exe = std::env::current_exe()
.map_err(|e| anyhow::anyhow!("cannot find this program to point the unit at: {e}"))?;
let sibling = exe.with_file_name("eclipse-gateway");
if sibling.is_file() {
return Ok(sibling);
}
bail!(
"no eclipse-gateway next to {}; re-run install.sh so the install has the gateway binary",
exe.display()
)
}
pub fn run(profile: Option<&str>, config: Option<&Path>) -> Result<()> {
let bin = web_bin()?;
let mut command = std::process::Command::new(&bin);
for (key, value) in service_env(profile, config) {
command.env(key, value);
}
use std::os::unix::process::CommandExt;
let err = command.exec();
bail!("could not start {}: {err}", bin.display())
}
pub fn install(style: &Style, profile: Option<&str>, config: Option<&Path>) -> Result<()> {
let gateway = web_bin()?;
let dir = units_dir()?;
std::fs::create_dir_all(&dir)?;
let home = std::env::var("HOME").unwrap_or_else(|_| "".into());
let docs = PathBuf::from(&home)
.join(".eclipse")
.join("docs")
.join("USER.md");
let service_path = dir.join(SERVICE_NAME);
let env = service_env(profile, config);
std::fs::write(&service_path, unit_text(&gateway, &docs, &env))?;
println!("{} {}", style.green("wrote"), service_path.display());
for (key, value) in &env {
println!("{} {key}={value}", style.dim(" pinned"));
}
let was_active = is_active();
let ran = std::process::Command::new("systemctl")
.args(["--user", "daemon-reload"])
.status()
.map(|s| s.success())
.unwrap_or(false)
&& std::process::Command::new("systemctl")
.args(["--user", "enable", "--now", SERVICE_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if ran {
if was_active {
let restarted = std::process::Command::new("systemctl")
.args(["--user", "restart", SERVICE_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !restarted {
bail!(
"the unit was rewritten and enabled, but the running gateway could not be \
restarted, so it is still serving the old one; by hand:\n \
systemctl --user restart {SERVICE_NAME}\n \
journalctl --user -u {SERVICE_NAME} --no-pager -n 30"
);
}
println!("{} {}", style.green("restarted"), SERVICE_NAME);
println!(
"{}",
style.dim(" the unit changed, so the running process was replaced by this build")
);
} else {
println!("{} {}", style.green("enabled"), SERVICE_NAME);
}
println!(
"{}",
style.dim(
" `systemctl --user status eclipse-gateway` shows one pid serving the dashboard and the API; \
`journalctl --user -u eclipse-gateway.service` shows the log"
)
);
println!(
"{}",
style.dim(&format!(
" the unit runs `{}` — re-install after an upgrade with `eclipse gateway install`",
gateway.display()
))
);
println!(
"{}",
style.dim(
" to run while you are logged out: loginctl enable-linger $USER (needs root)"
)
);
} else {
println!(
"{}",
style.yellow("systemctl did not take it; enable it by hand with:")
);
println!(" systemctl --user daemon-reload");
println!(" systemctl --user enable --now {SERVICE_NAME}");
bail!(
"the unit is written to {} but systemctl did not enable it — run the two commands above",
service_path.display()
);
}
Ok(())
}
pub fn installed_unit() -> Option<PathBuf> {
let dir = units_dir().ok()?;
let path = dir.join(SERVICE_NAME);
path.exists().then_some(path)
}
pub fn restart(style: &Style) -> Result<()> {
let service_path = units_dir()?.join(SERVICE_NAME);
if !service_path.exists() {
bail!(
"no unit at {} — `eclipse gateway install` writes one and enables it",
service_path.display()
);
}
let was_active = is_active();
let took_it = std::process::Command::new("systemctl")
.args(["--user", "restart", SERVICE_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !took_it {
bail!(
"systemctl could not restart {SERVICE_NAME}; it may still be running the old binary — \
`journalctl --user -u {SERVICE_NAME} --no-pager -n 30` says why"
);
}
match wait_active(Duration::from_secs(10)) {
Some(ms) => {
let verb = if was_active { "restarted" } else { "started" };
println!(
"{} {} (active after {ms} ms)",
style.green(verb),
SERVICE_NAME
);
Ok(())
}
None => bail!(
"{SERVICE_NAME} was restarted but is not active after 10s — \
`journalctl --user -u {SERVICE_NAME} --no-pager -n 30` says why"
),
}
}
pub(crate) fn is_active_text(stdout: &str) -> bool {
stdout.trim() == "active"
}
pub fn stop(style: &Style) -> Result<()> {
let took_it = std::process::Command::new("systemctl")
.args(["--user", "disable", "--now", SERVICE_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !took_it {
bail!(
"systemctl could not stop {SERVICE_NAME}; it may still be running — \
`eclipse gateway status` and `journalctl --user -u {SERVICE_NAME}` say what happened"
);
}
println!("{} {}", style.green("stopped and disabled"), SERVICE_NAME);
println!(
"{}",
style.dim(" to bring it back, and keep it coming back: eclipse gateway start")
);
Ok(())
}
pub fn start(style: &Style) -> Result<()> {
let service_path = units_dir()?.join(SERVICE_NAME);
if !service_path.exists() {
bail!(
"no unit at {} — `eclipse gateway install` writes one and enables it",
service_path.display()
);
}
if is_active() {
if is_enabled() == Some(true) {
println!(
"{} {}",
style.green("already up; nothing to do"),
SERVICE_NAME
);
return Ok(());
}
let enabled = std::process::Command::new("systemctl")
.args(["--user", "enable", SERVICE_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !enabled {
bail!(
"{SERVICE_NAME} is running but not enabled, so it would not survive a reboot, and \
systemctl would not enable it; by hand:\n \
systemctl --user enable {SERVICE_NAME}"
);
}
println!(
"{} {}",
style.green("already up; enabled it so it survives a reboot"),
SERVICE_NAME
);
return Ok(());
}
let took_it = std::process::Command::new("systemctl")
.args(["--user", "enable", "--now", SERVICE_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !took_it {
bail!(
"systemctl could not enable {SERVICE_NAME}; by hand:\n \
systemctl --user enable --now {SERVICE_NAME}\n \
journalctl --user -u {SERVICE_NAME} --no-pager -n 30"
);
}
match wait_active(Duration::from_secs(10)) {
Some(ms) => {
println!(
"{} {} (active after {ms} ms)",
style.green("started and enabled"),
SERVICE_NAME
);
println!(
"{}",
style.dim(" status: eclipse gateway status · down: eclipse gateway stop")
);
Ok(())
}
None => bail!(
"{SERVICE_NAME} was enabled but is not active after 10s — \
`journalctl --user -u {SERVICE_NAME} --no-pager -n 30` says why"
),
}
}
fn is_active() -> bool {
std::process::Command::new("systemctl")
.args(["--user", "is-active", SERVICE_NAME])
.output()
.map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "active")
.unwrap_or(false)
}
fn is_enabled() -> Option<bool> {
std::process::Command::new("systemctl")
.args(["--user", "is-enabled", SERVICE_NAME])
.output()
.ok()
.map(|o| String::from_utf8_lossy(&o.stdout).trim() == "enabled")
}
fn wait_active(budget: Duration) -> Option<u128> {
let started = std::time::Instant::now();
loop {
if is_active() {
return Some(started.elapsed().as_millis());
}
if started.elapsed() >= budget {
return None;
}
std::thread::sleep(Duration::from_millis(100));
}
}
pub fn uninstall(style: &Style) -> Result<()> {
let stopped = stop(style);
let path = units_dir()?.join(SERVICE_NAME);
if path.exists() {
std::fs::remove_file(&path)?;
println!("{} {}", style.green("removed"), path.display());
}
let _ = std::process::Command::new("systemctl")
.args(["--user", "daemon-reload"])
.status();
stopped
}
pub fn status(style: &Style) -> Result<()> {
let out = std::process::Command::new("systemctl")
.args(["--user", "is-active", SERVICE_NAME])
.output();
match out {
Ok(o) => {
let stdout = String::from_utf8_lossy(&o.stdout).trim().to_string();
if o.status.success() && stdout == "active" {
println!("{}", style.green("eclipse-gateway is up"));
let _ = std::process::Command::new("systemctl")
.args([
"--user",
"status",
SERVICE_NAME,
"--no-pager",
"--lines",
"20",
])
.status();
} else {
println!("{} {}", style.dim("eclipse-gateway:"), stdout);
let installed = units_dir()
.map(|d| d.join(SERVICE_NAME).exists())
.unwrap_or(false);
if !installed {
println!(
"{}",
style.dim(" not installed — `eclipse gateway install` writes the unit")
);
} else {
let enabled = match is_enabled() {
Some(true) => "enabled",
Some(false) => "disabled",
None => "enablement unknown",
};
println!(
"{}",
style.dim(&format!(
" installed, unit is {enabled} — `eclipse gateway start` brings it back"
))
);
}
std::process::exit(1);
}
}
Err(e) => bail!("systemctl did not answer: {e}"),
}
Ok(())
}
pub(crate) fn systemd_word(path: &std::path::Path) -> String {
let raw = path.display().to_string();
let mut out = String::with_capacity(raw.len() + 2);
out.push('"');
for c in raw.chars() {
if c == '"' || c == '\\' {
out.push('\\');
}
out.push(c);
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_unit_points_at_the_gateway_binary_and_restarts() {
let path = Path::new("/usr/local/bin/eclipse-gateway");
let docs = Path::new("/home/x/.eclipse/docs/USER.md");
let text = unit_text(path, docs, &[]);
assert!(
text.contains("ExecStart=\"/usr/local/bin/eclipse-gateway\""),
"{text}"
);
assert!(text.contains("Restart=always"));
assert!(text.contains("WantedBy=default.target"));
assert!(!text.contains("Environment="), "{text}");
}
#[test]
fn the_unit_carries_the_profile_and_the_config_it_was_installed_for() {
let path = Path::new("/usr/local/bin/eclipse-gateway");
let docs = Path::new("/home/x/.eclipse/docs/USER.md");
let env = service_env(Some("work"), Some(Path::new("/srv/eclipse/work.toml")));
let text = unit_text(path, docs, &env);
assert!(
text.contains("Environment=\"ECLIPSE_PROFILE=work\"\n"),
"{text}"
);
assert!(
text.contains("Environment=\"ECLIPSE_CONFIG=/srv/eclipse/work.toml\"\n"),
"{text}"
);
assert!(
text.contains("ExecStart=\"/usr/local/bin/eclipse-gateway\"\n"),
"{text}"
);
}
#[test]
fn a_path_with_spaces_or_quotes_survives_as_one_word() {
let spaced = Path::new("/home/ann/My Apps/eclipse/bin/eclipse-gateway");
let docs = Path::new("/home/ann/My Apps/eclipse/docs/USER.md");
let text = unit_text(spaced, docs, &[]);
assert!(
text.contains("ExecStart=\"/home/ann/My Apps/eclipse/bin/eclipse-gateway\""),
"the path is one quoted word: {text}"
);
let odd = Path::new("/tmp/we\"ird\\dir/eclipse-gateway");
assert_eq!(
systemd_word(odd),
"\"/tmp/we\\\"ird\\\\dir/eclipse-gateway\""
);
assert_eq!(
systemd_word(Path::new("/usr/local/bin/x")),
"\"/usr/local/bin/x\""
);
}
#[test]
fn a_profile_alone_pins_only_the_profile() {
let env = service_env(Some("work"), None);
assert_eq!(
env,
vec![("ECLIPSE_PROFILE".to_string(), "work".to_string())]
);
}
#[test]
fn a_relative_config_path_is_made_absolute() {
let env = service_env(None, Some(Path::new("conf/eclipse.toml")));
assert_eq!(env.len(), 1);
assert_eq!(env[0].0, "ECLIPSE_CONFIG");
let written = Path::new(&env[0].1);
assert!(written.is_absolute(), "{}", env[0].1);
assert!(written.ends_with("conf/eclipse.toml"), "{}", env[0].1);
}
}