#!/usr/bin/env python3
"""Drive the iDRAC SMASH/racadm CLI over SSH and print each command's output.

    python idrac_ssh.py "racadm getsvctag" "racadm netstat"

The iDRAC login shell is clpd (/admin1->), so commands are typed into a PTY.
Output is read until the channel has been idle for --idle seconds.
"""
import argparse
import sys
import time

import paramiko


def drain(ch, idle=2.5, maxwait=120, quiet=False):
    buf = b""
    start = time.time()
    last = time.time()
    while time.time() - start < maxwait:
        if ch.recv_ready():
            chunk = ch.recv(65535)
            buf += chunk
            last = time.time()
            tail = buf[-120:]
            if b"--More--" in tail or b"----More----" in tail:
                ch.send(" ")
        else:
            if buf and (time.time() - last) > idle:
                break
            time.sleep(0.05)
    return buf.decode("utf-8", "replace")


def connect(host, user, password):
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(host, username=user, password=password,
              look_for_keys=False, allow_agent=False,
              timeout=20, banner_timeout=20, auth_timeout=20)
    ch = c.invoke_shell(term="vt100", width=220, height=200)
    time.sleep(1.5)
    drain(ch, idle=0.8, maxwait=3)
    return c, ch


def run(ch, cmd, idle=2.5, maxwait=120):
    ch.send(cmd + "\n")
    return drain(ch, idle=idle, maxwait=maxwait)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("commands", nargs="+")
    ap.add_argument("--host", default="192.0.2.10")
    ap.add_argument("--user", default="operator")
    ap.add_argument("--password", default="REDACTED")
    ap.add_argument("--idle", type=float, default=2.5)
    ap.add_argument("--maxwait", type=float, default=120)
    a = ap.parse_args()

    c, ch = connect(a.host, a.user, a.password)
    try:
        for cmd in a.commands:
            print("### " + cmd)
            txt = run(ch, cmd, a.idle, a.maxwait)
            print(txt)
    finally:
        c.close()


if __name__ == "__main__":
    main()
