teter 26.11.5

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter ls`, `teter new` and `teter kill machine:session` (#79): signed
//! commands to one of the account's machines, through the relay (#88, #78).

use std::path::PathBuf;

use teter_common::command::{Command, Outcome};

/// List a machine's sessions.
#[derive(clap::Args)]
pub struct LsArgs {
    /// The machine, by its name in the account.
    machine: String,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Create a session on a machine and start it.
#[derive(clap::Args)]
pub struct NewArgs {
    /// The session, as `machine:session`.
    target: String,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// `machine:session` split, or an error naming the form.
fn split(target: &str) -> std::io::Result<(&str, &str)> {
    target
        .split_once(':')
        .filter(|(machine, session)| !machine.is_empty() && !session.is_empty())
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("{target:?} is not machine:session"),
            )
        })
}

/// Runs `command` on `machine`.
async fn run(
    machine: &str,
    ca_cert: Option<PathBuf>,
    command: Command,
) -> std::io::Result<Outcome> {
    let (mut channel, keys) = crate::sessions::command_channel(machine, ca_cert).await?;
    channel.run(&keys, command).await
}

/// `outcome` of a command that answers done, as a result.
fn done(outcome: Outcome) -> std::io::Result<()> {
    match outcome {
        Outcome::Done => Ok(()),
        Outcome::Failed { reason } => Err(std::io::Error::other(reason)),
        Outcome::Sessions { .. } => Err(std::io::Error::other("the machine answered a list")),
    }
}

/// One session of `teter ls`: its name and state, then, while it runs, the
/// frontends attached to it (from the relay, by its channel) and its
/// terminal's size (#135).
fn ls_line(
    session: &teter_common::command::SessionInfo,
    clients: &std::collections::HashMap<String, u32>,
) -> String {
    if !session.running {
        return format!("{}\tstopped\t-\t-", session.name);
    }
    // Every column always, `-` for what is not known, so a field keeps its
    // place.
    let clients = clients.get(&session.id).map_or_else(
        || "-".to_owned(),
        |count| {
            let noun = if *count == 1 { "client" } else { "clients" };
            format!("{count} {noun}")
        },
    );
    let size = session.size.map_or_else(
        || "-".to_owned(),
        |(columns, rows)| format!("{columns}x{rows}"),
    );
    format!("{}\trunning\t{clients}\t{size}", session.name)
}

/// `teter ls machine`.
pub async fn ls(args: LsArgs) -> std::io::Result<()> {
    let (mut channel, keys, clients) =
        crate::sessions::command_channel_and_clients(&args.machine, args.ca_cert).await?;
    match channel.run(&keys, Command::List).await? {
        Outcome::Sessions { sessions } => {
            for session in sessions {
                println!("{}", ls_line(&session, &clients));
            }
            Ok(())
        }
        Outcome::Failed { reason } => Err(std::io::Error::other(reason)),
        Outcome::Done => Err(std::io::Error::other("the machine answered no list")),
    }
}

/// `teter new machine:session`.
pub async fn new(args: NewArgs) -> std::io::Result<()> {
    let (machine, session) = split(&args.target)?;
    let command = Command::New {
        name: session.to_owned(),
    };
    done(run(machine, args.ca_cert, command).await?)?;
    println!("created {machine}:{session}");
    Ok(())
}

/// `teter kill machine:session`.
pub async fn kill(target: &str, ca_cert: Option<PathBuf>) -> std::io::Result<()> {
    let (machine, session) = split(target)?;
    let command = Command::Kill {
        name: session.to_owned(),
    };
    match run(machine, ca_cert, command).await? {
        Outcome::Failed { reason } if reason.starts_with("no session named") => {
            return Err(std::io::Error::other(format!(
                "{machine} has no session named {session:?} (see `teter ls {machine}`)"
            )));
        }
        outcome @ (Outcome::Done | Outcome::Sessions { .. } | Outcome::Failed { .. }) => {
            done(outcome)?;
        }
    }
    println!("ended {machine}:{session}");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use teter_common::command::SessionInfo;

    fn info(running: bool, size: Option<(u16, u16)>) -> SessionInfo {
        SessionInfo {
            name: "main".to_owned(),
            id: "c1".to_owned(),
            running,
            size,
        }
    }

    #[test]
    fn an_ls_line_keeps_its_columns_whatever_is_known() {
        let mut clients = std::collections::HashMap::new();
        assert_eq!(ls_line(&info(true, None), &clients), "main\trunning\t-\t-");
        assert_eq!(ls_line(&info(false, None), &clients), "main\tstopped\t-\t-");
        clients.insert("c1".to_owned(), 1);
        assert_eq!(
            ls_line(&info(true, Some((80, 24))), &clients),
            "main\trunning\t1 client\t80x24"
        );
        clients.insert("c1".to_owned(), 2);
        assert_eq!(
            ls_line(&info(true, None), &clients),
            "main\trunning\t2 clients\t-"
        );
    }
}