use std::thread::sleep;
use std::time::Duration;
use ssh_rs::{ChannelShell, Session, ssh};
use ssh_rs::key_pair::KeyPairType;

fn main() {
    let mut session: Session = ssh::create_session();
    let user_home = rust_util::util_os::get_user_home().unwrap();
    // pem format key path -> /xxx/xxx/id_rsa
    // KeyPairType::SshRsa -> Rsa type algorithm, currently only supports rsa.
    session.set_user_and_key_pair_path(
        "root",
        format!("{}/.ssh/id_rsa", user_home),
        KeyPairType::SshRsa,
    ).unwrap();
    session.connect("hatter.ink:22").unwrap();

    let exec = session.open_exec().unwrap();
    let v = exec.send_command("ls -l -a --color ~/").unwrap();
    println!("{}", String::from_utf8_lossy(&v).to_string());

    println!("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
    let mut shell: ChannelShell = session.open_shell().unwrap();
    run_shell(&mut shell);

    shell.close().ok();
    session.close().ok();
}

fn run_shell(shell: &mut ChannelShell) {
    sleep(Duration::from_millis(500));
    let vec = shell.read().unwrap();
    println!("{}", String::from_utf8(vec).unwrap());

    shell.write(b"ls\n").unwrap();

    sleep(Duration::from_millis(500));

    let vec = shell.read().unwrap();
    println!("{}", String::from_utf8(vec).unwrap());
}