#!/usr/bin/env python3
"""sshtest - test SSH connectivity to a host with timing and a banner grab.
Usage: sshtest HOST [PORT] [--selftest]
  Opens a TCP connection to the SSH port (default 22), times the connect,
  reads the server's SSH version banner (e.g. "SSH-2.0-OpenSSH_9.2"), and
  reports whether the port is open, how fast it answered, and what server
  is behind it — without authenticating or running an ssh client. Fails
  fast (3s timeout) with a clear message, never hangs.
"""
import argparse
import socket
import sys
import threading
import time


def test_ssh(host, port=22, timeout=3.0):
    """Return dict with ok, connect_ms, banner, error."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(timeout)
    t0 = time.monotonic()
    try:
        s.connect((host, port))
    except socket.gaierror as e:
        return {"ok": False, "error": f"DNS: {e}"}
    except OSError as e:
        return {"ok": False, "error": str(e)}
    connect_ms = (time.monotonic() - t0) * 1000
    banner = ""
    try:
        s.settimeout(2.0)
        data = s.recv(256)
        banner = data.decode("utf-8", "replace").strip().splitlines()[0] if data else ""
    except (socket.timeout, OSError):
        banner = ""
    finally:
        s.close()
    return {"ok": True, "connect_ms": connect_ms, "banner": banner}


def report(host, port, res):
    if not res["ok"]:
        print(f"sshtest: {host}:{port} — FAILED: {res['error']}")
        return 1
    print(f"sshtest: {host}:{port} — OPEN in {res['connect_ms']:.1f} ms")
    if res["banner"]:
        print(f"  banner: {res['banner']}")
        if res["banner"].startswith("SSH-2.0"):
            print("  protocol: SSH-2.0 (modern)")
        elif res["banner"].startswith("SSH-1."):
            print("  protocol: SSH-1.x (obsolete — investigate!)")
        else:
            print("  protocol: unrecognised banner (not an SSH server?)")
    else:
        print("  banner: (none received — port open but not speaking SSH?)")
    return 0


def selftest():
    # Serve a fake SSH banner on localhost so the test needs no real server.
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(("127.0.0.1", 0))
    port = srv.getsockname()[1]
    srv.listen(1)

    def serve():
        try:
            conn, _ = srv.accept()
            conn.sendall(b"SSH-2.0-OpenSSH_9.2p1 test\r\n")
            time.sleep(0.2)
            conn.close()
        except OSError:
            pass

    threading.Thread(target=serve, daemon=True).start()
    res = test_ssh("127.0.0.1", port)
    print(f"selftest: fake SSH server on 127.0.0.1:{port}")
    assert res["ok"] and res["banner"].startswith("SSH-2.0"), f"banner grab failed: {res}"
    rc = report("127.0.0.1", port, res)
    srv.close()
    refused = test_ssh("127.0.0.1", 1, timeout=1.0)
    assert not refused["ok"], "port 1 should refuse"
    print(f"selftest: banner grab + refused-port handling — OK (refused: {refused['error']})")
    return rc


def main():
    ap = argparse.ArgumentParser(description="sshtest - test SSH connectivity with timing and a banner grab")
    ap.add_argument("host", nargs="?", help="host to test")
    ap.add_argument("port", nargs="?", type=int, default=22, help="SSH port (default 22)")
    ap.add_argument("--timeout", type=float, default=3.0, help="connect timeout in seconds (default 3)")
    ap.add_argument("--selftest", action="store_true", help="banner-grab a fake SSH server on localhost")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if not args.host:
        ap.error("HOST is required (or use --selftest)")
    res = test_ssh(args.host, args.port, args.timeout)
    return report(args.host, args.port, res)


if __name__ == "__main__":
    sys.exit(main())
