//! Run a command in an existing sailbox and print its output.
//!
//! ```text
//! SAIL_API_KEY=sk_... cargo run --example exec -- sb_abc123 echo hello
//! ```

use sail::exec::ExecOptions;
use sail::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    let usage = "usage: exec <sailbox_id> <command> [args...]";
    let sailbox_id = args.next().ok_or(usage)?;
    let command: Vec<String> = args.collect();
    if command.is_empty() {
        return Err(usage.into());
    }

    let client = Client::from_env()?;
    let proc = client
        .exec(&sailbox_id, command, ExecOptions::default())
        .await?;
    let result = proc.wait().await?;

    print!("{}", result.stdout);
    eprint!("{}", result.stderr);
    if result.exit_code != 0 {
        eprintln!("command exited with code {}", result.exit_code);
    }
    Ok(())
}
