use lmrc_ssh::{AuthMethod, SshClient};

fn main() -> Result<(), lmrc_ssh::Error> {
    println!("SSH Manager - Public Key Authentication Example\n");

    // Get configuration from environment variables
    let host = std::env::var("SSH_HOST").unwrap_or_else(|_| "example.com".to_string());
    let username = std::env::var("SSH_USER").unwrap_or_else(|_| "user".to_string());
    let key_path = std::env::var("SSH_KEY_PATH")
        .unwrap_or_else(|_| format!("{}/.ssh/id_rsa", std::env::var("HOME").unwrap()));
    let passphrase = std::env::var("SSH_KEY_PASSPHRASE").ok();

    println!("Configuration:");
    println!("  Host: {}", host);
    println!("  User: {}", username);
    println!("  Key:  {}", key_path);
    println!(
        "  Passphrase: {}",
        if passphrase.is_some() {
            "provided"
        } else {
            "not provided"
        }
    );
    println!();

    println!("Connecting with public key authentication...");

    let mut client = SshClient::new(host, 22)?
        .with_auth(AuthMethod::PublicKey {
            username: username.clone(),
            private_key_path: key_path,
            passphrase,
        })
        .connect()?;

    println!("✓ Connected successfully!\n");

    // Execute some commands
    println!("Executing: whoami");
    let output = client.execute("whoami")?;
    println!("Output: {}", output.stdout.trim());

    println!("\nExecuting: hostname");
    let output = client.execute("hostname")?;
    println!("Output: {}", output.stdout.trim());

    println!("\nExecuting: ssh -V");
    let output = client.execute("ssh -V")?;
    if output.is_success() {
        println!("Output: {}", output.stdout.trim());
    } else {
        // ssh -V outputs to stderr on some systems
        println!("Output: {}", output.stderr.trim());
    }

    println!("\n✓ Public key authentication successful!");

    Ok(())
}
