#!/usr/bin/env python3
"""
eo - command line interface for EasyOps.

    eo login [URL]                      sign in (the session is kept in ~/.config/eo/config.json)
    eo logout                           sign out
    eo hosts                            list the hosts and whether they are online
    eo exec HOST COMMAND...             run a command on a host; output live, exit code passed on
    eo get HOST REMOTE [LOCAL|-]        download a file from a host (- writes it to stdout)
    eo put HOST LOCAL REMOTE            upload a file to a host (REMOTE may be a folder)
    eo log HOST FILE [-n LINES]         show the end of a file and follow it until Ctrl+C
    eo ls HOST [PATH]                   list a folder on a host
    eo shell HOST                       interactive shell on a host (Linux/FreeBSD)
    eo ai [HOST] PROMPT...              let Claude carry out a prompt on a host (no HOST: all hosts)
    eo info HOST                        system information of a host
    eo update-agent HOST                install the server's agent version on a host

Short forms: eo-exec, eo-get, eo-put, eo-log (a link named eo-<command> runs that command).
Environment: EO_URL and EO_TOKEN override the stored login.
Only the Python standard library is used.
"""

import argparse
import base64
import getpass
import http.client
import json
import os
import queue
import shutil
import signal
import socket
import ssl
import struct
import sys
import threading
import time
import uuid
from pathlib import Path
from urllib.parse import urlparse

VERSION = "1.0.0"
COOKIE = "easyops_session"
DEFAULT_URL = "https://easyops.rocketai.info"
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "eo" / "config.json"
CHUNK = 192 * 1024  # upload chunk; the server takes up to 256 KB per chunk


class EoError(Exception):
    pass


def die(text: str, code: int = 1):
    print(f"eo: {text}", file=sys.stderr)
    sys.exit(code)


# ---------------------------------------------------------------------------
# Login
# ---------------------------------------------------------------------------

def load_config() -> dict:
    try:
        cfg = json.loads(CONFIG.read_text())
    except (OSError, ValueError):
        cfg = {}
    if os.environ.get("EO_URL"):
        cfg["url"] = os.environ["EO_URL"]
    if os.environ.get("EO_TOKEN"):
        cfg["token"] = os.environ["EO_TOKEN"]
    return cfg


def save_config(cfg: dict):
    CONFIG.parent.mkdir(parents=True, exist_ok=True)
    tmp = CONFIG.with_suffix(".tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(cfg, f, indent=2)
    os.replace(tmp, CONFIG)


def need_login() -> dict:
    cfg = load_config()
    if not cfg.get("url") or not cfg.get("token"):
        die("not signed in - run: eo login")
    return cfg


def http_request(url: str, method: str, path: str, body=None, token: str | None = None):
    u = urlparse(url)
    conn_cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
    conn = conn_cls(u.hostname, u.port, timeout=30)
    headers = {"Content-Type": "application/json", "User-Agent": f"eo/{VERSION}"}
    if token:
        headers["Cookie"] = f"{COOKIE}={token}"
    try:
        conn.request(method, path, json.dumps(body) if body is not None else None, headers)
        resp = conn.getresponse()
        data = resp.read()
    except OSError as e:
        raise EoError(f"cannot reach {url}: {e}")
    finally:
        conn.close()
    try:
        payload = json.loads(data) if data else {}
    except ValueError:
        payload = {}
    return resp, payload


def api(cfg: dict, method: str, path: str, body=None):
    resp, payload = http_request(cfg["url"], method, path, body, cfg["token"])
    if resp.status == 401:
        die("the session has expired - run: eo login")
    if resp.status >= 400:
        die(payload.get("detail") or payload.get("error") or f"HTTP {resp.status}")
    return payload


def cmd_login(args):
    cfg = load_config()
    url = (args.url or input(f"EasyOps URL [{cfg.get('url') or DEFAULT_URL}]: ").strip()
           or cfg.get("url") or DEFAULT_URL).rstrip("/")
    if "://" not in url:
        url = "https://" + url
    username = args.user or input("Username: ").strip()
    password = getpass.getpass("Password: ")
    resp, payload = http_request(url, "POST", "/api/auth/signin", {"username": username, "password": password})
    if resp.status != 200:
        die(payload.get("error") or f"sign-in failed (HTTP {resp.status})")
    token = None
    for header, value in resp.getheaders():
        if header.lower() == "set-cookie" and value.startswith(COOKIE + "="):
            token = value.split(";", 1)[0].split("=", 1)[1]
    if not token:
        die("the server sent no session")
    save_config({"url": url, "token": token, "user": payload.get("username", username)})
    print(f"Signed in to {url} as {payload.get('username', username)}")


def cmd_logout(_args):
    cfg = load_config()
    if cfg.get("url") and cfg.get("token"):
        try:
            http_request(cfg["url"], "POST", "/api/auth/signout", {}, cfg["token"])
        except EoError:
            pass
    try:
        CONFIG.unlink()
    except FileNotFoundError:
        pass
    print("Signed out")


# ---------------------------------------------------------------------------
# WebSocket (RFC 6455, client side, text frames only)
# ---------------------------------------------------------------------------

class WS:
    def __init__(self, cfg: dict):
        u = urlparse(cfg["url"])
        port = u.port or (443 if u.scheme == "https" else 80)
        try:
            sock = socket.create_connection((u.hostname, port), timeout=30)
            if u.scheme == "https":
                sock = ssl.create_default_context().wrap_socket(sock, server_hostname=u.hostname)
        except OSError as e:
            raise EoError(f"cannot reach {cfg['url']}: {e}")
        key = base64.b64encode(os.urandom(16)).decode()
        host = u.hostname if u.port is None else f"{u.hostname}:{u.port}"
        sock.sendall((
            f"GET /ws HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
            f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n"
            f"Cookie: {COOKIE}={cfg['token']}\r\nUser-Agent: eo/{VERSION}\r\n\r\n").encode())
        self.sock, self.buf = sock, b""
        head = b""
        while b"\r\n\r\n" not in head:
            chunk = sock.recv(4096)
            if not chunk:
                raise EoError("the server closed the connection")
            head += chunk
        head, self.buf = head.split(b"\r\n\r\n", 1)
        status = head.split(b"\r\n", 1)[0].decode(errors="replace")
        if " 403" in status:
            die("the session has expired - run: eo login")
        if " 101 " not in status + " ":
            raise EoError(f"WebSocket refused: {status}")
        sock.settimeout(None)
        self.lock = threading.Lock()
        self.inbox: queue.Queue = queue.Queue()
        threading.Thread(target=self._reader, daemon=True).start()

    def _read(self, n: int) -> bytes:
        while len(self.buf) < n:
            chunk = self.sock.recv(65536)
            if not chunk:
                raise ConnectionError("closed")
            self.buf += chunk
        data, self.buf = self.buf[:n], self.buf[n:]
        return data

    def _frame(self, opcode: int, payload: bytes):
        mask = os.urandom(4)
        n = len(payload)
        if n < 126:
            head = struct.pack("!BB", 0x80 | opcode, 0x80 | n)
        elif n < 65536:
            head = struct.pack("!BBH", 0x80 | opcode, 0x80 | 126, n)
        else:
            head = struct.pack("!BBQ", 0x80 | opcode, 0x80 | 127, n)
        masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) if n < 4096 else \
            (int.from_bytes(payload, "big") ^ int.from_bytes((mask * (n // 4 + 1))[:n], "big")).to_bytes(n, "big")
        with self.lock:
            self.sock.sendall(head + mask + masked)

    def _reader(self):
        message, close_code = b"", None
        try:
            while True:
                b1, b2 = self._read(2)
                opcode, n = b1 & 0x0F, b2 & 0x7F
                if n == 126:
                    n = struct.unpack("!H", self._read(2))[0]
                elif n == 127:
                    n = struct.unpack("!Q", self._read(8))[0]
                payload = self._read(n)  # the server does not mask
                if opcode == 0x8:
                    close_code = struct.unpack("!H", payload[:2])[0] if len(payload) >= 2 else 1000
                    break
                if opcode == 0x9:
                    self._frame(0xA, payload)
                    continue
                if opcode in (0x1, 0x2, 0x0):
                    message += payload
                    if b1 & 0x80:
                        try:
                            self.inbox.put(json.loads(message))
                        except ValueError:
                            pass
                        message = b""
        except (OSError, ConnectionError, struct.error, ValueError):
            pass
        self.inbox.put({"type": "_closed", "code": close_code})

    def send(self, msg: dict):
        try:
            self._frame(0x1, json.dumps(msg).encode())
        except OSError:
            pass

    def recv(self, timeout: float | None = None) -> dict | None:
        try:
            msg = self.inbox.get(timeout=timeout)
        except queue.Empty:
            return None
        if msg.get("type") == "_closed":
            if msg.get("code") == 4401:
                die("the session has expired - run: eo login")
            raise EoError("connection to EasyOps lost")
        return msg

    def call(self, msg: dict, result_type: str, timeout: float = 120) -> dict:
        """Send a request and wait for its answer."""
        rid = msg.setdefault("id", uuid.uuid4().hex)
        self.send(msg)
        deadline = time.time() + timeout
        while True:
            left = deadline - time.time()
            if left <= 0:
                raise EoError("no answer from EasyOps")
            reply = self.recv(left)
            if reply and reply.get("id") == rid and reply.get("type") in (result_type, "error"):
                return reply


def connect() -> WS:
    return WS(need_login())


def fail_message(res: dict) -> str:
    return res.get("message") or res.get("error") or "failed"


# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------

def get_hosts(cfg: dict) -> list[dict]:
    return api(cfg, "GET", "/api/hosts").get("hosts", [])


def host_os(cfg: dict, hostname: str) -> str:
    for h in get_hosts(cfg):
        if h["hostname"] == hostname:
            return h.get("os") or "linux"
    die(f"unknown host: {hostname}")


def cmd_hosts(args):
    hosts = get_hosts(need_login())
    if args.json:
        print(json.dumps(hosts, indent=2))
        return
    tty = sys.stdout.isatty()
    green, red, dim, reset = ("\033[32m", "\033[31m", "\033[2m", "\033[0m") if tty else ("",) * 4
    width = max([len(h["hostname"]) for h in hosts] + [4])
    for h in sorted(hosts, key=lambda h: h["hostname"]):
        state = f"{green}online {reset}" if h.get("online") else f"{red}offline{reset}"
        extra = []
        if h.get("version"):
            extra.append(f"agent {h['version']}" + (" (update available)" if h.get("update_available") else ""))
        if h.get("os") and h["os"] != "linux":
            extra.append(h["os"])
        if h.get("last_ip"):
            extra.append(h["last_ip"])
        for d in h.get("low_disks") or []:
            extra.append(f"low disk {d['mount']} {d['percent_free']:.0f}% free")
        print(f"{h['hostname']:<{width}}  {state}  {dim}{'  '.join(extra)}{reset}")


def run_exec(ws: WS, host: str, command: str, timeout: int, out=None) -> int:
    """Run a command on a host, writing its output to out as it comes. -> exit code."""
    out = out or sys.stdout
    rid = uuid.uuid4().hex
    ws.send({"id": rid, "type": "exec", "hostname": host, "command": command, "timeout": timeout})
    interrupted = False
    while True:
        try:
            msg = ws.recv()
        except KeyboardInterrupt:
            if interrupted:
                die("interrupted", 130)
            interrupted = True
            ws.send({"id": rid, "type": "exec_cancel", "hostname": host})
            continue
        if msg.get("id") != rid:
            continue
        if msg["type"] == "exec_output":
            out.write(msg.get("data", ""))
            out.flush()
        elif msg["type"] == "error":
            die(fail_message(msg))
        elif msg["type"] == "exec_finished":
            if not msg.get("ok"):
                die(msg.get("error") or "the command could not be run")
            if msg.get("cancelled"):
                print("eo: stopped", file=sys.stderr)
                return 130
            if msg.get("timed_out"):
                print(f"eo: killed after the timeout of {timeout}s", file=sys.stderr)
                return 124
            code = msg.get("exit_code")
            return code if isinstance(code, int) and 0 <= code < 256 else 1


def cmd_exec(args):
    command = " ".join(args.command)
    if not command.strip():
        die("no command given")
    sys.exit(run_exec(connect(), args.host, command, args.timeout))


def cmd_log(args):
    cfg = need_login()
    path = args.file
    if host_os(cfg, args.host) == "windows":
        ps_path = path.lstrip("/") if len(path) > 2 and path[2] == ":" else path
        command = f"Get-Content -LiteralPath '{ps_path.replace(chr(39), chr(39) * 2)}' -Tail {args.lines} -Wait"
    else:
        quoted = "'" + path.replace("'", "'\\''") + "'"
        command = f"tail -n {args.lines} -F {quoted}" if not args.no_follow else f"tail -n {args.lines} {quoted}"
    try:
        code = run_exec(WS(cfg), args.host, command, 24 * 3600)
    except KeyboardInterrupt:
        code = 0
    sys.exit(0 if code == 130 else code)


def list_dir(ws: WS, host: str, path: str) -> dict:
    return ws.call({"type": "list_dir", "hostname": host, "path": path}, "list_dir_result", 30)


def remote_path(path: str) -> str:
    if not path.startswith("/"):
        die(f"the path on the host must be absolute: {path}")
    return path


def cmd_get(args):
    ws = connect()
    path = remote_path(args.remote)
    local = args.local or os.path.basename(path.rstrip("/")) or "download"
    to_stdout = local == "-"
    if not to_stdout and os.path.isdir(local):
        local = os.path.join(local, os.path.basename(path.rstrip("/")))
    tmp = None if to_stdout else f"{local}.eo-part"
    out = sys.stdout.buffer if to_stdout else open(tmp, "wb")
    offset, size, started = 0, 0, time.time()
    progress = not to_stdout and sys.stderr.isatty()
    try:
        while True:
            res = ws.call({"type": "get_file_chunk", "hostname": args.host, "path": path, "offset": offset},
                          "get_file_chunk_result", 120)
            if not res.get("ok"):
                raise EoError(fail_message(res))
            data = base64.b64decode(res.get("data") or "")
            out.write(data)
            offset, size = res.get("offset") or offset + len(data), res.get("size") or 0
            if progress:
                pct = f"{offset * 100 // size}%" if size else ""
                print(f"\r{path}: {offset:,} / {size:,} bytes {pct}", end="", file=sys.stderr)
            if not res.get("more"):
                break
    except (EoError, KeyboardInterrupt) as e:
        if tmp:
            out.close()
            os.unlink(tmp)
        die(str(e) or "interrupted")
    if tmp:
        out.close()
        os.replace(tmp, local)
        if progress:
            print(file=sys.stderr)
        print(f"{args.host}:{path} -> {local} ({offset:,} bytes, {time.time() - started:.1f}s)", file=sys.stderr)
    else:
        out.flush()


def cmd_put(args):
    ws = connect()
    if not os.path.isfile(args.local):
        die(f"no such file: {args.local}")
    path = remote_path(args.remote)
    name = os.path.basename(args.local)
    if path.endswith("/"):
        path += name
    else:
        res = list_dir(ws, args.host, path)
        if res.get("ok"):  # an existing folder: the file goes into it
            path = path.rstrip("/") + "/" + name
    size, sent, started = os.path.getsize(args.local), 0, time.time()
    progress = sys.stderr.isatty()
    with open(args.local, "rb") as f:
        first = True
        while True:
            data = f.read(CHUNK)
            final = f.tell() >= size or not data
            res = ws.call({"type": "put_file_chunk", "hostname": args.host, "path": path,
                           "data": base64.b64encode(data).decode(), "first": first, "final": final,
                           "make_dirs": args.parents}, "put_file_chunk_result", 120)
            if not res.get("ok"):
                die(fail_message(res))
            first, sent = False, sent + len(data)
            if progress:
                pct = f"{sent * 100 // size}%" if size else ""
                print(f"\r{path}: {sent:,} / {size:,} bytes {pct}", end="", file=sys.stderr)
            if final:
                break
    if progress:
        print(file=sys.stderr)
    print(f"{args.local} -> {args.host}:{path} ({sent:,} bytes, {time.time() - started:.1f}s)", file=sys.stderr)


def human_size(n) -> str:
    if n is None:
        return "-"
    for unit in ("B", "K", "M", "G", "T"):
        if n < 1024 or unit == "T":
            return f"{n:.0f}{unit}" if unit == "B" else f"{n:.1f}{unit}"
        n /= 1024


def cmd_ls(args):
    path = remote_path(args.path)
    res = list_dir(connect(), args.host, path)
    if not res.get("ok"):
        die(fail_message(res))
    entries = sorted(res.get("entries", []), key=lambda e: (e["type"] != "dir", e["name"]))
    for e in entries:
        mtime = time.strftime("%Y-%m-%d %H:%M", time.localtime(e["mtime"])) if e.get("mtime") else " " * 16
        name = e["name"] + ("/" if e["type"] == "dir" else "") + (" @" if e.get("link") else "")
        size = "" if e["type"] == "dir" else human_size(e.get("size"))
        print(f"{mtime}  {size:>7}  {name}")
    if res.get("truncated"):
        print("eo: the listing was cut off", file=sys.stderr)


def cmd_shell(args):
    if not sys.stdin.isatty():
        die("eo shell needs a terminal")
    import termios
    import tty
    ws = connect()
    rid = uuid.uuid4().hex
    cols, rows = shutil.get_terminal_size()
    ws.send({"id": rid, "type": "open_terminal", "hostname": args.host, "cols": cols, "rows": rows})

    def on_resize(*_):
        c, r = shutil.get_terminal_size()
        ws.send({"id": rid, "type": "script_resize", "hostname": args.host, "cols": c, "rows": r})

    fd = sys.stdin.fileno()
    saved = termios.tcgetattr(fd)
    done = threading.Event()
    result = {"code": 0}

    def pump():
        try:
            while True:
                msg = ws.recv()
                if msg.get("id") != rid:
                    continue
                if msg["type"] == "script_output":
                    os.write(sys.stdout.fileno(), msg.get("data", "").encode())
                elif msg["type"] == "script_finished":
                    result["code"] = msg.get("exit_code", 0)
                    break
        except (EoError, SystemExit) as e:
            result["error"] = str(e)
        done.set()

    signal.signal(signal.SIGWINCH, on_resize)
    tty.setraw(fd)
    threading.Thread(target=pump, daemon=True).start()
    try:
        import select
        while not done.is_set():
            ready, _, _ = select.select([fd], [], [], 0.2)
            if ready:
                data = os.read(fd, 65536)
                if not data:
                    break
                ws.send({"id": rid, "type": "script_input", "hostname": args.host,
                         "data": data.decode(errors="replace")})
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, saved)
    if result.get("error"):
        die(result["error"])
    code = result["code"]
    sys.exit(code if isinstance(code, int) and 0 <= code < 256 else 1)


def cmd_ai(args):
    cfg = need_login()
    words = list(args.prompt)
    host = None
    if len(words) > 1 and words[0] in {h["hostname"] for h in get_hosts(cfg)}:
        host = words.pop(0)
    elif args.host:
        host = args.host
    prompt = " ".join(words).strip()
    if not prompt:
        die("no prompt given")
    ws = WS(cfg)
    tty = sys.stderr.isatty()
    dim, cyan, red, reset = ("\033[2m", "\033[36m", "\033[31m", "\033[0m") if tty else ("",) * 4
    rid, session = uuid.uuid4().hex, uuid.uuid4().hex
    ws.send({"id": rid, "type": "ai_run", "hostname": host, "prompt": prompt, "session": session, "html": False})
    interrupted = False
    while True:
        try:
            msg = ws.recv()
        except KeyboardInterrupt:
            if interrupted:
                die("interrupted", 130)
            interrupted = True
            ws.send({"id": rid, "type": "ai_cancel", "hostname": host, "session": session})
            continue
        if msg.get("id") != rid:
            continue
        t = msg["type"]
        if t == "ai_text":
            sys.stdout.write(msg.get("text", ""))
            sys.stdout.flush()
        elif t == "ai_command":
            where = f"{msg['host']}" if msg.get("host") else (host or "")
            sys.stdout.flush()
            print(f"\n{cyan}$ {where + ': ' if where and not host else ''}{msg['command']}{reset}", file=sys.stderr)
        elif t == "ai_output" and not args.quiet:
            sys.stderr.write(dim + msg.get("data", "") + reset)
            sys.stderr.flush()
        elif t == "ai_command_done":
            if msg.get("error"):
                print(f"{red}{msg['error']}{reset}", file=sys.stderr)
            elif not args.quiet:
                state = "stopped" if msg.get("cancelled") else "timed out" if msg.get("timed_out") \
                    else f"exit {msg.get('exit_code')}"
                print(f"{dim}[{state}, {msg.get('duration')}s]{reset}", file=sys.stderr)
        elif t == "ai_finished":
            print()
            if msg.get("cancelled"):
                print("eo: stopped", file=sys.stderr)
                sys.exit(130)
            if not msg.get("ok"):
                die(msg.get("error") or "the run failed")
            return


def cmd_info(args):
    res = connect().call({"type": "system_info", "hostname": args.host}, "system_info_result", 60)
    if not res.get("ok"):
        die(fail_message(res))
    print(json.dumps(res.get("info", {}), indent=2))


def cmd_update_agent(args):
    res = connect().call({"type": "update_agent", "hostname": args.host}, "update_agent_result", 150)
    print(res.get("message") or ("done" if res.get("ok") else "failed"))
    sys.exit(0 if res.get("ok") else 1)


# ---------------------------------------------------------------------------

def parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(prog="eo", description="Command line interface for EasyOps.")
    p.add_argument("--version", action="version", version=f"eo {VERSION}")
    sub = p.add_subparsers(dest="cmd", metavar="COMMAND")

    s = sub.add_parser("login", help="sign in")
    s.add_argument("url", nargs="?")
    s.add_argument("-u", "--user")
    s.set_defaults(func=cmd_login)

    sub.add_parser("logout", help="sign out").set_defaults(func=cmd_logout)

    s = sub.add_parser("hosts", help="list the hosts")
    s.add_argument("--json", action="store_true", help="print the full host data as JSON")
    s.set_defaults(func=cmd_hosts)

    s = sub.add_parser("exec", help="run a command on a host")
    s.add_argument("-t", "--timeout", type=int, default=600, help="seconds until the command is killed (600)")
    s.add_argument("host")
    s.add_argument("command", nargs=argparse.REMAINDER)
    s.set_defaults(func=cmd_exec)

    s = sub.add_parser("get", help="download a file from a host")
    s.add_argument("host")
    s.add_argument("remote")
    s.add_argument("local", nargs="?", help="local file or folder; - for stdout (default: ./NAME)")
    s.set_defaults(func=cmd_get)

    s = sub.add_parser("put", help="upload a file to a host")
    s.add_argument("-p", "--parents", action="store_true", help="create missing folders on the host")
    s.add_argument("host")
    s.add_argument("local")
    s.add_argument("remote", help="absolute path or folder on the host")
    s.set_defaults(func=cmd_put)

    s = sub.add_parser("log", help="follow a file on a host (tail -f)")
    s.add_argument("-n", "--lines", type=int, default=50)
    s.add_argument("--no-follow", action="store_true", help="only print the last lines")
    s.add_argument("host")
    s.add_argument("file")
    s.set_defaults(func=cmd_log)

    s = sub.add_parser("ls", help="list a folder on a host")
    s.add_argument("host")
    s.add_argument("path", nargs="?", default="/")
    s.set_defaults(func=cmd_ls)

    s = sub.add_parser("shell", help="interactive shell on a host")
    s.add_argument("host")
    s.set_defaults(func=cmd_shell)

    s = sub.add_parser("ai", help="let Claude carry out a prompt (first word may be a host)")
    s.add_argument("-H", "--host", help="the host (default: all hosts, unless the first word is one)")
    s.add_argument("-q", "--quiet", action="store_true", help="do not print the commands' output")
    s.add_argument("prompt", nargs=argparse.REMAINDER)
    s.set_defaults(func=cmd_ai)

    s = sub.add_parser("info", help="system information of a host")
    s.add_argument("host")
    s.set_defaults(func=cmd_info)

    s = sub.add_parser("update-agent", help="update the agent on a host")
    s.add_argument("host")
    s.set_defaults(func=cmd_update_agent)
    return p


def main():
    argv = sys.argv[1:]
    name = os.path.basename(sys.argv[0])
    if name.startswith("eo-"):  # eo-exec, eo-get, ... run that command
        argv = [name[3:]] + argv
    p = parser()
    args = p.parse_args(argv)
    if not getattr(args, "func", None):
        p.print_help()
        sys.exit(2)
    try:
        args.func(args)
    except EoError as e:
        die(str(e))
    except KeyboardInterrupt:
        die("interrupted", 130)
    except BrokenPipeError:
        sys.exit(0)


if __name__ == "__main__":
    main()
