hop_cli/utils/
sudo.rs

1use anyhow::{Context, Result};
2use tokio::process::Command;
3
4pub async fn fix() -> Result<()> {
5    // check if in sudo and user real user home
6    if let Ok(user) = std::env::var("USER") {
7        if user != "root" {
8            return Ok(()); // not in sudo
9        }
10
11        if let Ok(user) = std::env::var("SUDO_USER") {
12            log::debug!("Running as SUDO, using home of `{user}`");
13
14            // running ~user to get home path
15            let home = Command::new("sh")
16                .arg("-c")
17                .arg(format!("eval echo ~{user}"))
18                .output()
19                .await
20                .with_context(|| format!("Failed to get home path of `{user}`"))?
21                .stdout;
22
23            let home = String::from_utf8(home)?;
24
25            log::debug!("Setting home to `{home}`");
26
27            // set home path
28            std::env::set_var("HOME", home.trim());
29        } else {
30            log::debug!("Running as root without sudo, using home `{user}`");
31        }
32    }
33
34    Ok(())
35}