pub(crate) const LOGIN_SHELL: &str = "if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi";
pub(crate) const CONTAINER_SHELL: &str = "if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi";
pub(crate) fn login_shell_as(user: &str) -> String {
format!("if [ $(id -un) = {user} ]; then {LOGIN_SHELL}; else exec sudo -iu {user}; fi")
}
pub(crate) fn container_shell_as() -> String {
format!("cd 2>/dev/null; {LOGIN_SHELL}")
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[test]
fn the_scripts_as_an_account_are_sh() {
for script in [login_shell_as("user"), container_shell_as()] {
let parsed = std::process::Command::new("sh").args(["-n", "-c", &script]).status();
assert!(parsed.is_ok_and(|s| s.success()), "{script}");
}
}
#[test]
fn a_login_as_an_account_is_the_sessions_shell_or_a_sudo_into_it() {
for (session, said) in [("user", "bash -l\n"), ("vagrant", "sudo -iu user\n")] {
let bin = tempfile::tempdir().unwrap();
for (tool, says) in [
("id", format!("echo {session}")),
("sudo", "echo \"sudo $*\"".into()),
("bash", "echo \"bash $*\"".into()),
] {
isothrum_test_support::write_executable(&bin.path().join(tool), &format!("#!/bin/sh\n{says}\n")).unwrap();
}
let path = format!("{}:{}", bin.path().display(), std::env::var("PATH").unwrap_or_default());
let out = std::process::Command::new("sh")
.args(["-c", &login_shell_as("user")])
.env("PATH", path)
.output()
.unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout), said, "as {session}");
}
}
}