vce 0.1.1

A stateful virtual OS engine with an embeddable machine and shell API
Documentation
//! The VCE application: a playable virtual machine.
//!
//! Boots a virtual OS, logs in, and gives you a real shell against it:
//!
//! ```text
//! vce                        interactive terminal (mirrors the host identity)
//! vce --os macos             boot macOS instead of Linux
//! vce --user rey             explicit standard user (password = username)
//! echo "ls /" | vce          scripted line mode (no terminal)
//! ```
//!
//! Interactive mode is the terminal spike: the virtual terminal
//! model is rendered onto the host console, `man`/`nano` use the alternate
//! screen, and keys are forwarded while commands run.

use std::io::IsTerminal;
use std::time::{SystemTime, UNIX_EPOCH};

use engine::Timestamp;
use os::HostIdentity;
use vce::{Machine, OsKind, Session};

/// The supported command-line flags.
struct Options {
    /// The OS to boot.
    os: OsKind,
    /// The shell to boot into; `None` follows the user's `$SHELL`.
    shell: Option<vce::ShellChoice>,
    /// The standard user name (on Unix the password is the same as the
    /// name; on Windows the account's password is used).
    user: Option<String>,
    /// An explicit logon password (Windows); when absent and the account
    /// has one, vce prompts.
    password: Option<String>,
    /// The boot time, in virtual nanoseconds.
    boot_time: Timestamp,
}

fn main() {
    let arguments: Vec<String> = std::env::args().skip(1).collect();
    if arguments
        .iter()
        .any(|argument| argument == "--help" || argument == "-h")
    {
        println!("{}", usage());
        return;
    }
    if arguments.iter().any(|argument| argument == "--version") {
        println!("vce {}", env!("CARGO_PKG_VERSION"));
        return;
    }
    let options = match parse_args(arguments) {
        Ok(options) => options,
        Err(message) => {
            eprintln!("{message}");
            std::process::exit(2);
        }
    };

    let identity = match &options.user {
        Some(user) => {
            let host = HostIdentity::from_host();
            HostIdentity::new(user.clone(), host.hostname())
        }
        None => HostIdentity::from_host(),
    };

    let machine = match Machine::builder(options.os)
        .username(identity.username())
        .hostname(identity.hostname())
        .boot_time(options.boot_time)
        .build()
    {
        Ok(machine) => machine,
        Err(error) => {
            eprintln!("boot failed: {error}");
            std::process::exit(1);
        }
    };
    let interactive = std::io::stdin().is_terminal();
    let session = if interactive && options.password.is_none() {
        machine.interactive_session(options.shell)
    } else {
        let password = options
            .password
            .as_deref()
            .unwrap_or_else(|| machine.default_user());
        machine.login(machine.default_user(), password, options.shell)
    };
    let session = match session {
        Ok(session) => session,
        Err(error) => {
            eprintln!("login failed: {error}");
            std::process::exit(1);
        }
    };
    run_session(session);
}

/// Runs a session interactively on a terminal, in line mode otherwise.
fn run_session<'os>(session: Session<'os>) -> ! {
    let status = if std::io::stdin().is_terminal() {
        session.run_interactive()
    } else {
        let mut stdin = std::io::stdin();
        session.run_line(&mut stdin)
    };
    std::process::exit(status);
}

/// Parses command-line flags.
fn parse_args(args: Vec<String>) -> Result<Options, String> {
    let mut os_choice = OsKind::Linux;
    let mut shell = None;
    let mut user = None;
    let mut password = None;
    let mut index = 0;
    while index < args.len() {
        match args[index].as_str() {
            "--os" => {
                index += 1;
                let value = args
                    .get(index)
                    .ok_or_else(|| "missing value for --os".to_owned())?;
                os_choice = match value.as_str() {
                    "linux" => OsKind::Linux,
                    "macos" => OsKind::MacOS,
                    "windows" => OsKind::Windows,
                    other => {
                        return Err(format!("unknown OS '{other}' (linux, macos, windows)"));
                    }
                };
            }
            "--shell" => {
                index += 1;
                let value = args
                    .get(index)
                    .ok_or_else(|| "missing value for --shell".to_owned())?;
                shell = Some(match value.as_str() {
                    "bash" => vce::ShellChoice::Bash,
                    "zsh" => vce::ShellChoice::Zsh,
                    "powershell" | "pwsh" => vce::ShellChoice::PowerShell,
                    "cmd" => vce::ShellChoice::Cmd,
                    other => {
                        return Err(format!(
                            "unknown shell '{other}' (bash, zsh, powershell, cmd; the default follows the OS's default shell)"
                        ));
                    }
                });
            }
            "--user" => {
                index += 1;
                user = Some(
                    args.get(index)
                        .ok_or_else(|| "missing value for --user".to_owned())?
                        .clone(),
                );
            }
            "--password" => {
                index += 1;
                password = Some(
                    args.get(index)
                        .ok_or_else(|| "missing value for --password".to_owned())?
                        .clone(),
                );
            }
            other => {
                return Err(format!("unknown argument '{other}'\n{}", usage()));
            }
        }
        index += 1;
    }
    let boot_time = Timestamp::from_nanos(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
            .try_into()
            .unwrap_or(u64::MAX),
    );
    Ok(Options {
        os: os_choice,
        shell,
        user,
        password,
        boot_time,
    })
}

/// The usage message.
fn usage() -> String {
    "usage: vce [--os linux|macos|windows] [--shell bash|zsh|powershell|cmd] [--user NAME] [--password WORD] [--help] [--version]".to_owned()
}