#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Vantax server check: what on this server needs fixing, in plain English.

Free for every UK business. Looks only at THIS machine. Reads versions and
settings, changes nothing, sends nothing anywhere, needs no extra software.

    python3 vantax-check.py            plain-English report
    sudo python3 vantax-check.py       fuller report (reads a few root-only settings)
    python3 vantax-check.py --json     the same, as JSON
    python3 vantax-check.py --demo     example report for a made-up server
    python3 vantax-check.py --version

Exit code: 0 nothing to do, 1 something needs attention, 2 couldn't run.

What it checks
  - Is the operating system still getting security updates?
  - Are security updates waiting to be installed? (apt, dnf, yum)
  - Does the server need a restart to finish installing updates?
  - PHP: the two critical flaws fixed on 21 October 2026 (CVE-2026-109618 and
    CVE-2026-109619), and PHP versions that no longer get fixes
  - xz 5.6.0 and 5.6.1, the two releases that shipped with a backdoor
    (CVE-2024-3094)
  - OpenSSH and sudo built by hand, outside the package manager: regreSSHion
    (CVE-2024-6387) and the sudo chroot flaw (CVE-2025-32463)
  - SSH: does it accept passwords, and can root log in with one?
  - Databases listening on the network (MySQL, PostgreSQL, Redis, MongoDB...)
  - Are automatic security updates switched on?
  - WordPress sites it can see (version only, no verdict)

Commands it runs, all read-only: `<program> -v / -V / --version` on the
programs it finds, `dpkg -S`, `dpkg-query -W`, `rpm -qf`, `apt list
--upgradable`, `dnf/yum updateinfo list` (from the local cache only),
`systemctl is-enabled`, `ss -ltn`, `sshd -T` (when run as root) and
`apachectl -M`.

Honest limits
  It reads version numbers and settings. Linux distributions often fix a flaw
  without changing the version number ("backporting"), so for software from
  the system's own packages it trusts the package manager's list of waiting
  security updates, which is only as fresh as the server's last update check.
  It is not a penetration test and can't promise a server is safe. It can't
  see shared hosting you don't control.

Not affiliated with or endorsed by the NCSC or the UK government.
"""
import datetime
import glob
import json
import os
import re
import shutil
import subprocess
import sys
import textwrap

VERSION = "0.3.1"
CHECKED = "2026-10-26"  # the day the advisory and support lists below were last checked

ROOT = ""  # test hook: --root DIR reads files and finds programs under DIR instead of /
HOST_TOOLS = ("ss", "apt", "apt-get", "dnf", "yum", "systemctl")  # skipped under --root

# ---------------------------------------------------------------------------
# What it knows. Update CHECKED when any of this changes.
# ---------------------------------------------------------------------------

# PHP: CVE-2026-109618 / CVE-2026-109619, fixed 21 October 2026.
PHP_CVES = "CVE-2026-109618 / CVE-2026-109619"
PHP_FIXED = {(8, 5): 12, (8, 4): 27, (8, 3): 36, (8, 2): 35}
PHP_SOURCE_PATCH_ONLY = {(7, 4), (8, 0), (8, 1)}  # limited source patches; no releases
PHP_GLOBS = [
    "/usr/bin/php", "/usr/bin/php[0-9]*", "/usr/local/bin/php", "/usr/local/bin/php[0-9]*",
    "/usr/sbin/php-fpm*", "/usr/local/sbin/php-fpm*",
    "/opt/plesk/php/*/bin/php", "/opt/plesk/php/*/sbin/php-fpm",
    "/opt/remi/php*/root/usr/bin/php", "/opt/remi/php*/root/usr/sbin/php-fpm",
    "/opt/cpanel/ea-php*/root/usr/bin/php", "/opt/alt/php*/usr/bin/php-cgi",
    "/usr/local/php*/bin/php", "/usr/local/lsws/lsphp*/bin/lsphp",
    "/opt/psa/admin/bin/php", "/usr/local/psa/admin/bin/php",  # the PHP that runs the Plesk panel itself
]
PANEL_PHP = ("/opt/psa/", "/usr/local/psa/")

# Other programs: (name, places, version flag, version pattern).
TOOLS = [
    ("openssh", ["/usr/sbin/sshd", "/usr/local/sbin/sshd", "/usr/local/bin/sshd"], "-V",
     r"OpenSSH_(\d+\.\d+(?:p\d+)?)"),
    ("sudo", ["/usr/bin/sudo", "/usr/local/bin/sudo", "/bin/sudo"], "-V",
     r"Sudo version (\d+\.\d+\.\d+(?:p\d+)?)"),
    ("xz", ["/usr/bin/xz", "/usr/local/bin/xz", "/bin/xz"], "--version",
     r"xz \(XZ Utils\) (\d+\.\d+\.\d+)"),
]
OPENSSH_LATEST = ((10, 5, 0), "10.5", "August 2026")  # newest release with security fixes
SUDO_FIXED = (1, 9, 17, 1)  # 1.9.17p1 fixed CVE-2025-32463 and CVE-2025-32462

# End of security updates: (date compared against, how to say it).
# Ubuntu: ubuntu.com/about/release-cycle and the release team's list of releases.
UBUNTU = {
    "14.04": ("2019-04-30", "April 2019"), "16.04": ("2021-04-30", "April 2021"),
    "18.04": ("2023-05-31", "May 2023"), "20.04": ("2025-05-31", "May 2025"),
    "22.04": ("2027-05-31", "2027"), "24.04": ("2029-05-31", "2029"), "26.04": ("2031-05-31", "2031"),
    "23.10": ("2024-07-11", "July 2024"), "24.10": ("2025-07-10", "July 2025"),
    "25.04": ("2026-01-15", "January 2026"), "25.10": ("2026-07-31", "July 2026"),
    "26.10": ("2027-07-31", "July 2027"),
}
UBUNTU_ESM = {"18.04": "May 2028", "20.04": "May 2030", "22.04": "2032", "24.04": "2034", "26.04": "2036"}
# Debian: debian.org news (Debian 11 LTS ended 31 August 2026; Debian 12 LTS runs to 30 June 2028).
DEBIAN = {
    "8": ("2020-06-30", "June 2020"), "9": ("2022-06-30", "June 2022"), "10": ("2024-06-30", "June 2024"),
    "11": ("2026-08-31", "31 August 2026"), "12": ("2028-06-30", "30 June 2028"),
}

DB_PORTS = {3306: "MySQL/MariaDB", 5432: "PostgreSQL", 6379: "Redis", 27017: "MongoDB",
            11211: "Memcached", 9200: "Elasticsearch/OpenSearch", 5984: "CouchDB"}

WP_ROOTS = [
    "/var/www/html", "/var/www/*", "/var/www/*/htdocs", "/var/www/*/httpdocs", "/var/www/*/public_html",
    "/var/www/*/public", "/var/www/*/html", "/var/www/vhosts/*/httpdocs", "/var/www/vhosts/*/httpdocs/*",
    "/var/www/vhosts/*/*", "/home/*/public_html", "/home/*/public_html/*", "/home/*/www", "/srv/www/*",
    "/srv/www/*/public_html", "/usr/share/nginx/html",
]

# ---------------------------------------------------------------------------
# Reading the machine (read-only)
# ---------------------------------------------------------------------------


def fs(path):
    return ROOT + path


def shown(path):
    return path[len(ROOT):] if ROOT and path.startswith(ROOT) else path


def read_abs(path, limit=400000):
    try:
        with open(path, "r", errors="replace") as f:
            return f.read(limit)
    except (OSError, ValueError):
        return None


def read(path, limit=400000):
    return read_abs(fs(path), limit)


def which(name):
    if ROOT and name in HOST_TOOLS:
        return None
    return shutil.which(name)


def run(cmd, timeout=20, merge=True):
    """Run a read-only command; its output as text, or '' on any failure."""
    env = dict(os.environ)
    env["LC_ALL"] = "C"
    env["LANG"] = "C"
    try:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL,
                             stderr=subprocess.STDOUT if merge else subprocess.DEVNULL, env=env)
    except (OSError, ValueError):
        return ""
    try:
        out, _ = p.communicate(timeout=timeout)
    except Exception:
        try:
            p.kill()
            p.communicate(timeout=5)
        except Exception:
            pass
        return ""
    return (out or b"").decode("utf-8", "replace")


def parse_version(text):
    """(major, minor, patch) from 'PHP 8.3.6 (cli) ...' or '8.3.6-1ubuntu1', else None."""
    m = re.search(r"(?<![\d.])(\d+)\.(\d+)\.(\d+)", text or "")
    return tuple(int(x) for x in m.groups()) if m else None


def vt(raw, n):
    """'9.6p1' -> (9, 6, 1); '1.9.17p1' -> (1, 9, 17, 1); padded or cut to n numbers."""
    parts = [int(x) for x in re.findall(r"\d+", raw or "")][:n]
    return tuple(parts + [0] * (n - len(parts)))


def natkey(s):
    return [(0, int(t)) if t.isdigit() else (1, t) for t in re.split(r"(\d+)", s) if t != ""]


def to_date(s):
    y, m, d = (int(x) for x in s.split("-"))
    return datetime.date(y, m, d)


def owner(path):
    """Who installed a file: 'distro' (system packages: fixes may be backported without
    changing the version number), 'upstream' (packaged, but tracks the upstream version:
    Plesk, cPanel, Remi, Sury) or 'hand' (no package owns it)."""
    p = shown(path)
    if p.startswith(PANEL_PHP):
        return "panel"
    if p.startswith(("/opt/plesk/", "/opt/cpanel/", "/opt/remi/")):
        return "upstream"
    if shutil.which("dpkg"):
        out = run(["dpkg", "-S", path])
        for line in out.splitlines():
            if ": /" in line and not line.startswith(("dpkg", "diversion")):
                pkg = line.split(":")[0].split(",")[0].strip()
                ver = run(["dpkg-query", "-W", "-f=${Version}", pkg], merge=False)
                return "upstream" if "sury" in ver.lower() else "distro"
    if shutil.which("rpm"):
        out = run(["rpm", "-qf", "--qf", "%{NAME}|%{VENDOR}\n", path]).strip()
        low = out.lower()
        if out and "not owned" not in low and "no such" not in low and "error" not in low:
            name, _, vendor = out.splitlines()[0].partition("|")
            if name.startswith("ea-php") or "remi" in vendor.lower() or "cpanel" in vendor.lower():
                return "upstream"
            return "distro"
    return "hand"


def find_execs(patterns):
    found = {}
    for pattern in patterns:
        for p in glob.glob(fs(pattern)):
            real = os.path.realpath(p)
            if os.path.isfile(real) and os.access(real, os.X_OK):
                found.setdefault(real, p)
    return found


def gather_os():
    text = read("/etc/os-release") or read("/usr/lib/os-release")
    if not text:
        return None
    kv = {}
    for line in text.splitlines():
        k, sep, v = line.partition("=")
        if sep:
            kv[k.strip()] = v.strip().strip('"').strip("'")
    return {"id": kv.get("ID", "").lower(), "version": kv.get("VERSION_ID", ""),
            "name": kv.get("PRETTY_NAME") or kv.get("NAME") or "", "like": kv.get("ID_LIKE", "").lower(),
            "esm": bool(glob.glob(fs("/etc/apt/sources.list.d/*esm-infra*")))}


def detect_panel():
    if any(os.path.exists(fs(p)) for p in ("/etc/psa/psa.conf", "/opt/psa", "/usr/local/psa", "/opt/plesk")):
        return "plesk"
    if os.path.isdir(fs("/usr/local/cpanel")):
        return "cpanel"
    return None


def detect_pkg():
    if which("apt-get") and shutil.which("dpkg"):
        return "apt"
    if which("dnf"):
        return "dnf"
    if which("yum"):
        return "yum"
    return None


def parse_listeners(text):
    """Ports something listens on beyond this machine, from `ss -ltn` output."""
    ports = set()
    for line in text.splitlines():
        parts = line.split()
        if len(parts) < 4 or parts[0] == "State":
            continue
        addr, _, port = parts[3].rpartition(":")
        if not port.isdigit():
            continue
        addr = addr.strip("[]").split("%")[0]
        if addr.startswith("127.") or addr in ("::1", "localhost") or addr.startswith("::ffff:127."):
            continue
        ports.add(int(port))
    return sorted(ports)


def gather_listeners():
    if not which("ss"):
        return None
    out = run(["ss", "-ltn"], merge=False)
    return parse_listeners(out) if out.strip() else None


def parse_apt(text):
    """Package names with a waiting security update, from `apt list --upgradable`."""
    names = []
    for line in text.splitlines():
        m = re.match(r"^([^/\s]+)/(\S+)\s", line)
        if m and "-security" in m.group(2):
            names.append(m.group(1))
    return sorted(set(names))


def parse_updateinfo(text):
    """Package names from `dnf/yum updateinfo list --security`."""
    names = set()
    for line in text.splitlines():
        parts = line.split()
        if len(parts) >= 3 and re.match(r"^[A-Z][A-Z0-9]*-\d{4}[:-]", parts[0]):
            m = re.match(r"^(.+?)-\d", parts[-1])
            names.add(m.group(1) if m else parts[-1])
    return sorted(names)


def gather_updates(pkg):
    if pkg == "apt":
        names = parse_apt(run(["apt", "list", "--upgradable"], timeout=90, merge=False))
        stamps = [os.path.getmtime(p) for p in glob.glob(fs("/var/lib/apt/lists/*Release"))]
        age = None
        if stamps:
            age = int((datetime.datetime.now().timestamp() - max(stamps)) // 86400)
        return {"known": True, "count": len(names), "names": names, "age_days": age}
    if pkg in ("dnf", "yum"):
        if pkg == "dnf":
            out = run(["dnf", "-q", "--cacheonly", "updateinfo", "list", "--security"], timeout=90)
        else:
            out = run(["yum", "-q", "-C", "updateinfo", "list", "security"], timeout=90)
        names = parse_updateinfo(out)
        if not names and re.search(r"(?i)error|cache.only|no cache|metadata", out):
            return {"known": False, "count": 0, "names": [], "age_days": None}
        return {"known": True, "count": len(names), "names": names, "age_days": None}
    return None


def gather_reboot():
    for f in ("/run/reboot-required", "/var/run/reboot-required"):
        if read(f) is not None:
            pkgs = (read(f + ".pkgs") or "").split()
            return {"needed": True, "why": "updates", "pkgs": sorted(set(pkgs))}
    running = (read("/proc/sys/kernel/osrelease") or "").strip()
    kernels = [os.path.basename(p)[len("vmlinuz-"):] for p in glob.glob(fs("/boot/vmlinuz-*"))]
    kernels = [k for k in kernels if "rescue" not in k]
    if running and running in kernels:
        flavour = lambda k: re.sub(r"[\d._-]+", "", k)
        same = [k for k in kernels if flavour(k) == flavour(running)]
        newest = max(same, key=natkey)
        if natkey(newest) > natkey(running):
            return {"needed": True, "why": "kernel", "running": running, "newest": newest}
    return {"needed": False}


def gather_php():
    found = find_execs(PHP_GLOBS)
    if not ROOT:
        for name in ("php", "php-cgi", "php-fpm"):
            w = shutil.which(name)
            if w:
                found.setdefault(os.path.realpath(w), w)
    out = []
    for real in sorted(found):
        ver = parse_version(run([real, "-v"]))
        if ver:
            out.append({"path": shown(real), "version": list(ver), "origin": owner(real)})
    return out


def gather_tools():
    out = []
    for name, places, flag, pattern in TOOLS:
        seen = set()
        for place in places:
            p = fs(place)
            if not (os.path.isfile(p) and os.access(p, os.X_OK)):
                continue
            real = os.path.realpath(p)
            if real in seen:
                continue
            seen.add(real)
            m = re.search(pattern, run([real, flag], timeout=10))
            if m:
                out.append({"name": name, "path": shown(real), "raw": m.group(1), "origin": owner(real)})
    return out


def running_php():
    if ROOT:
        return []
    names = set()
    for comm in glob.glob("/proc/[0-9]*/comm"):
        n = (read_abs(comm, 100) or "").strip()
        if n.startswith(("php-fpm", "php-cgi", "lsphp", "frankenphp")) or re.match(r"^php\d.*fpm", n):
            names.add(n)
    for apache in ("apachectl", "apache2ctl", "httpd"):
        if shutil.which(apache):
            if re.search(r"php\d?_module", run([apache, "-M"], timeout=10)):
                names.add("apache mod_php")
            break
    return sorted(names)


def parse_sshd_config(path="/etc/ssh/sshd_config"):
    """Effective global sshd settings from the files: the first value of each keyword
    wins, Include is followed, and Match blocks (which only apply to some logins) are
    skipped."""
    settings, ports, where = {}, [], {}

    def walk(p, depth, top):
        text = read(p)
        if text is None or depth > 8:
            return True
        for raw in text.splitlines():
            line = raw.strip()
            if not line or line.startswith("#"):
                continue
            m = re.match(r"^(\S+?)(?:\s*=\s*|\s+)(.*)$", line)
            if not m:
                continue
            key, val = m.group(1).lower(), m.group(2).strip().strip('"')
            if key == "match":
                return not top  # a Match block in an included file ends with that file
            if key == "include":
                for pat in val.split():
                    if not pat.startswith("/"):
                        pat = "/etc/ssh/" + pat
                    for inc in sorted(glob.glob(fs(pat))):
                        if not walk(shown(inc), depth + 1, False):
                            return False
                continue
            if key == "port":
                ports.append(val)
                continue
            settings.setdefault(key, val.lower())
            where.setdefault(key, p)
        return True

    walk(path, 0, True)
    settings["port"] = ports or ["22"]
    settings["_where"] = where
    settings["_dropin"] = bool(re.search(r"(?im)^\s*Include\s+\S*sshd_config\.d", read(path) or ""))
    return settings


def gather_ssh(listeners):
    if not any(os.path.isfile(fs(p)) for p in ("/usr/sbin/sshd", "/usr/local/sbin/sshd")):
        return None
    files = parse_sshd_config()
    eff, source = {}, "config files"
    if not ROOT and hasattr(os, "geteuid") and os.geteuid() == 0:
        sshd = "/usr/sbin/sshd" if os.path.isfile("/usr/sbin/sshd") else "/usr/local/sbin/sshd"
        ports = []
        for line in run([sshd, "-T"], timeout=15, merge=False).splitlines():
            k, _, v = line.partition(" ")
            if k == "port":
                ports.append(v.strip())
            elif k:
                eff.setdefault(k.lower(), v.strip().lower())
        if "passwordauthentication" in eff:
            eff["port"] = ports or ["22"]
            source = "sshd -T"
        else:
            eff = {}
    if not eff:
        eff = files
    kbd = eff.get("kbdinteractiveauthentication", eff.get("challengeresponseauthentication", "yes"))
    passwords = eff.get("passwordauthentication", "yes") == "yes" or (kbd == "yes" and eff.get("usepam", "no") == "yes")
    ports = [p for p in eff.get("port", ["22"]) if p.isdigit()]
    exposed = None
    if listeners is not None:
        exposed = any(int(p) in listeners for p in ports)
    return {"passwords": passwords, "root": eff.get("permitrootlogin", "prohibit-password"),
            "ports": ports, "exposed": exposed, "source": source, "dropin": files["_dropin"],
            "set_in": files["_where"].get("passwordauthentication")}


def gather_auto(pkg):
    if ROOT:
        return None
    if pkg == "apt":
        if not (os.path.exists("/usr/bin/unattended-upgrade") or os.path.exists("/usr/bin/unattended-upgrades")):
            return "off"
        value = None
        for f in sorted(glob.glob("/etc/apt/apt.conf.d/*")):
            for m in re.finditer(r'APT::Periodic::Unattended-Upgrade\s+"(\d+)"', read_abs(f) or ""):
                value = m.group(1)
        return "on" if value not in (None, "0") else "off"
    if pkg in ("dnf", "yum") and which("systemctl"):
        def enabled(unit):
            return run(["systemctl", "is-enabled", unit], timeout=10, merge=False).strip() == "enabled"
        if pkg == "yum":
            return "on" if enabled("yum-cron.service") else "off"
        if enabled("dnf-automatic-install.timer") or enabled("dnf5-automatic.timer"):
            return "on"
        if enabled("dnf-automatic.timer"):
            conf = read("/etc/dnf/automatic.conf") or ""
            return "on" if re.search(r"(?im)^\s*apply_updates\s*=\s*(yes|true|1)\b", conf) else "download-only"
        return "off"
    return None


def gather_wordpress():
    seen, versions = set(), []
    for root in WP_ROOTS:
        for vf in glob.glob(fs(root) + "/wp-includes/version.php"):
            real = os.path.realpath(vf)
            if real in seen or len(seen) >= 300:
                continue
            seen.add(real)
            m = re.search(r"\$wp_version\s*=\s*'([^']+)'", read_abs(real, 20000) or "")
            if m:
                versions.append(m.group(1))
    return sorted(versions, key=natkey)


def gather(today=None):
    facts = {"today": today or datetime.date.today().isoformat(), "demo": False, "errors": [],
             "root": bool(hasattr(os, "geteuid") and os.geteuid() == 0 and not ROOT)}

    def safe(name, fn, default):
        try:
            return fn()
        except Exception as e:  # one broken check must never stop the others
            facts["errors"].append("%s (%s)" % (name, e.__class__.__name__))
            return default

    facts["os"] = safe("operating system", gather_os, None)
    facts["panel"] = safe("control panel", detect_panel, None)
    facts["pkg"] = safe("package manager", detect_pkg, None)
    facts["listeners"] = safe("open ports", gather_listeners, None)
    facts["updates"] = safe("security updates", lambda: gather_updates(facts["pkg"]), None)
    facts["reboot"] = safe("restart", gather_reboot, None)
    facts["php"] = safe("PHP", gather_php, [])
    facts["running_php"] = safe("running PHP", running_php, [])
    facts["tools"] = safe("OpenSSH, sudo and xz", gather_tools, [])
    facts["ssh"] = safe("SSH settings", lambda: gather_ssh(facts["listeners"]), None)
    facts["auto"] = safe("automatic updates", lambda: gather_auto(facts["pkg"]), None)
    facts["wordpress"] = safe("WordPress", gather_wordpress, [])
    return facts


# ---------------------------------------------------------------------------
# Judging what was found
# ---------------------------------------------------------------------------


def finding(status, key, text, steps=None, share=None):
    return {"status": status, "key": key, "text": text, "steps": list(steps or []), "share": share}


def judge_php(ver, distro):
    """(status, what to say after 'PHP x.y.z ...'). status: ok | fix | check | old."""
    major, minor, patch = ver
    branch = (major, minor)
    if branch in PHP_FIXED:
        need = "%d.%d.%d" % (major, minor, PHP_FIXED[branch])
        if patch >= PHP_FIXED[branch]:
            return "ok", "has the fix for %s (needs %s or newer)." % (PHP_CVES, need)
        if distro:
            return "check", ("is older than the fixed %s, but it came from your system's own packages, which "
                             "may have fixed it without changing the number. Make sure every update is installed, "
                             "then check your vendor's security notice for %s." % (need, PHP_CVES))
        return "fix", ("is VULNERABLE to %s: attackers can run code on the server without logging in. "
                       "Update to %s or newer." % (PHP_CVES, need))
    if branch in PHP_SOURCE_PATCH_ONLY or branch < (8, 1):
        return "old", ("no longer gets security releases. Move to a supported PHP (8.2 to 8.5), or get "
                       "written confirmation that your vendor ships a fix for %s." % PHP_CVES)
    if branch > (8, 5):
        return "check", "is newer than the versions this check knows. Make sure it is a current release."
    return "old", "is not a version this check recognises as fixed. Update it."


def install_cmd(pkg):
    return {"apt": "sudo apt-get update && sudo apt-get upgrade", "dnf": "sudo dnf upgrade --security",
            "yum": "sudo yum update --security"}.get(pkg)


def refresh_cmd(pkg):
    return {"apt": "sudo apt-get update", "dnf": "sudo dnf makecache", "yum": "sudo yum makecache"}.get(pkg)


def php_steps(path, origin, facts):
    pkg = facts.get("pkg")
    upgrade = {"apt": None, "dnf": "sudo dnf upgrade", "yum": "sudo yum update"}.get(pkg) or "sudo dnf upgrade"
    if path.startswith(("/opt/plesk/",) + PANEL_PHP):
        return ["In Plesk: Tools & Settings > Updates (\"Updates and Upgrades\" on older Plesk), then install the "
                "available updates. They include Plesk's PHP versions.",
                "Restart PHP-FPM afterwards, or reboot at a quiet time."]
    if path.startswith("/opt/cpanel/"):
        return [upgrade + " 'ea-php*'", "Restart PHP-FPM afterwards (WHM > Restart Services), or reboot at a quiet time."]
    if path.startswith("/opt/remi/"):
        return [upgrade + " 'php*'", "Restart PHP-FPM afterwards, or reboot at a quiet time."]
    if origin in ("distro", "upstream") and pkg == "apt":
        return ["sudo apt-get update && sudo apt-get install --only-upgrade 'php*'",
                "sudo systemctl restart 'php*-fpm'   (and restart Apache if it uses mod_php)"]
    if origin in ("distro", "upstream") and pkg in ("dnf", "yum"):
        return [upgrade + " 'php*'", "sudo systemctl restart php-fpm"]
    return ["Update it the way it was installed: a newer build from php.net, or ask whoever set the server up."]


def eval_os(o, today):
    if not o:
        return finding("info", "os", "Couldn't tell which operating system this is.", share="os:unknown")
    i, v = o["id"], o["version"]
    name = o["name"] or ("%s %s" % (i, v)).strip()
    tag = "os:%s-%s" % (i or "unknown", v or "?")
    if i == "ubuntu":
        if v in UBUNTU:
            end, said = UBUNTU[v]
            if today <= to_date(end):
                return finding("ok", "os", "%s gets security updates until %s." % (name, said), share=tag + " ok")
            if o.get("esm") and v in UBUNTU_ESM:
                return finding("ok", "os", "%s's standard support ended in %s, but Ubuntu Pro (ESM) is switched on, "
                                     "so security fixes continue until %s." % (name, said, UBUNTU_ESM[v]),
                               share=tag + " esm")
            steps = []
            if v in UBUNTU_ESM:
                steps.append("Either switch on Ubuntu Pro (Canonical's extended support) to keep getting fixes until %s: "
                             "sudo pro attach YOUR-TOKEN   (token from ubuntu.com/pro)" % UBUNTU_ESM[v])
            steps.append("Or upgrade to a supported release, one LTS at a time: take a backup or snapshot first, "
                         "then: sudo do-release-upgrade")
            return finding("old", "os", "%s stopped getting security updates in %s." % (name, said), steps, tag + " OLD")
        m = re.match(r"^(\d+)\.(\d+)$", v)
        if m:
            yy, mm = int(m.group(1)), int(m.group(2))
            if not (mm == 4 and yy % 2 == 0) and (yy, mm) < (26, 10):
                return finding("old", "os", "%s was a short-term release and no longer gets security updates." % name,
                               ["Upgrade to a supported release: back up first, then: sudo do-release-upgrade"],
                               tag + " OLD")
        return finding("info", "os", "%s is newer than the releases this check knows." % name, share=tag)
    if i == "debian":
        if v in DEBIAN:
            end, said = DEBIAN[v]
            if today <= to_date(end):
                lts = " (through Debian LTS)" if v == "12" else ""
                return finding("ok", "os", "%s gets security updates until %s%s." % (name, said, lts), share=tag + " ok")
            return finding("old", "os", "%s stopped getting security updates on %s." % (name, said),
                           ["Upgrade to Debian 12 or 13, one release at a time: back up first and follow the "
                            "official release notes for each step."], tag + " OLD")
        if v.isdigit() and int(v) >= 13:
            return finding("ok", "os", "%s is a current Debian release and gets security updates." % name, share=tag + " ok")
        if v.isdigit() and int(v) < 8:
            return finding("old", "os", "%s is long out of support." % name,
                           ["Move to a supported Debian release, ideally on a fresh server."], tag + " OLD")
        return finding("info", "os", "Couldn't judge support for %s (a testing or unstable release?)." % name, share=tag)
    major = v.split(".")[0]
    move = ["Move to a supported system such as AlmaLinux or Rocky Linux (both have tools to convert from CentOS), "
            "or rebuild on a new server. Back up first."]
    if i == "centos":
        stream = "stream" in name.lower()
        if stream and major == "8":
            return finding("old", "os", "CentOS Stream 8 stopped getting updates on 31 May 2024.", move, tag + " OLD")
        if stream and major.isdigit() and int(major) >= 9:
            return finding("ok", "os", "%s is still getting updates." % name, share=tag + " ok")
        if major == "7":
            return finding("old", "os", "CentOS Linux 7 stopped getting updates on 30 June 2024.", move, tag + " OLD")
        if major == "8":
            return finding("old", "os", "CentOS Linux 8 stopped getting updates on 31 December 2021.", move, tag + " OLD")
        if major.isdigit() and int(major) < 7:
            return finding("old", "os", "%s is long out of support." % name, move, tag + " OLD")
    if i in ("rhel", "ol", "cloudlinux", "almalinux", "rocky") and major.isdigit():
        if int(major) >= 8:
            return finding("ok", "os", "%s is still supported." % name, share=tag + " ok")
        if int(major) == 7:
            return finding("check", "os", "%s: version 7's normal support has ended. You only get security fixes if "
                                          "you pay for extended support (for example RHEL ELS or TuxCare)." % name,
                           ["Confirm you have extended support, and plan a move to version 9 or 10."], tag + " CHECK")
        return finding("old", "os", "%s is long out of support." % name, ["Move to a supported release."], tag + " OLD")
    if i == "fedora" and v.isdigit():
        if int(v) <= 41:
            return finding("old", "os", "Fedora %s no longer gets updates." % v,
                           ["Upgrade to a current Fedora release (back up first): sudo dnf system-upgrade"], tag + " OLD")
        return finding("info", "os", "Fedora releases get about 13 months of updates: check %s is still current." % name,
                       share=tag)
    return finding("info", "os", "Couldn't judge support for %s: check its end-of-life date." % name, share=tag)


def eval_tools(tools, pkg):
    out, packaged = [], []
    for t in tools:
        name, raw, path, origin = t["name"], t["raw"], t["path"], t["origin"]
        if name == "xz":
            if vt(raw, 3) in ((5, 6, 0), (5, 6, 1)):
                steps = {"apt": ["sudo apt-get update && sudo apt-get install --only-upgrade xz-utils liblzma5"],
                         "dnf": ["sudo dnf upgrade xz xz-libs"], "yum": ["sudo yum update xz xz-libs"]}.get(
                    pkg, ["Replace it with a current xz release from your system's packages."])
                out.append(finding("fix", "xz", "xz %s at %s is one of the two releases that shipped with a backdoor "
                                               "(CVE-2024-3094)." % (raw, path), steps, "xz %s FIX" % raw))
            else:
                out.append(finding("ok", "xz", "xz %s is not one of the backdoored releases." % raw))
            continue
        if origin != "hand":
            packaged.append("%s %s" % ("OpenSSH" if name == "openssh" else name, raw))
            continue
        if name == "openssh":
            v = vt(raw, 3)
            update = ["Update to OpenSSH %s or newer, or switch back to your system's openssh-server package."
                      % OPENSSH_LATEST[1]]
            if (8, 5, 1) <= v < (9, 8, 1) or v < (4, 4, 1):
                out.append(finding("fix", "openssh", "OpenSSH %s at %s was built by hand and is open to regreSSHion "
                                                     "(CVE-2024-6387): attackers can run code as root without logging "
                                                     "in." % (raw, path), update, "openssh %s hand FIX" % raw))
            elif v < OPENSSH_LATEST[0]:
                out.append(finding("check", "openssh", "OpenSSH %s at %s was built by hand and is older than %s (%s), "
                                                       "which has later security fixes." % (raw, path, OPENSSH_LATEST[1],
                                                                                           OPENSSH_LATEST[2]),
                                   update, "openssh %s hand CHECK" % raw))
            else:
                out.append(finding("ok", "openssh", "OpenSSH %s (built by hand) is up to date." % raw))
        elif name == "sudo":
            v = vt(raw, 4)
            update = ["Update sudo to 1.9.17p1 or newer, or switch back to your system's sudo package."]
            if (1, 9, 14, 0) <= v < SUDO_FIXED:
                out.append(finding("fix", "sudo", "sudo %s at %s was built by hand and is open to CVE-2025-32463: a "
                                                  "local user can get root even if they aren't allowed to use sudo."
                                   % (raw, path), update, "sudo %s hand FIX" % raw))
            elif v < SUDO_FIXED:
                out.append(finding("check", "sudo", "sudo %s at %s was built by hand and is older than 1.9.17p1, the "
                                                    "release that fixed two privilege-escalation flaws." % (raw, path),
                                   update, "sudo %s hand CHECK" % raw))
            else:
                out.append(finding("ok", "sudo", "sudo %s (built by hand) has the 2025 fixes." % raw))
    if packaged:
        out.append(finding("info", "packaged", "%s %s from your system's own packages, so %s fixes arrive with "
                                               "the system's security updates." % (join(packaged),
                                                                                   "come" if len(packaged) > 1 else "comes",
                                                                                   "their" if len(packaged) > 1 else "its")))
    return out


def join(items):
    items = list(items)
    if len(items) <= 1:
        return "".join(items)
    return ", ".join(items[:-1]) + " and " + items[-1]


def few(names, n=6):
    names = list(names)
    if len(names) <= n:
        return join(names)
    return ", ".join(names[:n]) + " and %d more" % (len(names) - n)


def evaluate(facts):
    today = to_date(facts["today"])
    pkg = facts.get("pkg")
    out = [eval_os(facts.get("os"), today)]

    u = facts.get("updates")
    if u is not None:
        if not u["known"]:
            out.append(finding("check", "lists", "Couldn't read the list of waiting security updates without "
                                                 "refreshing it.", [refresh_cmd(pkg) or "Refresh the package lists"],
                               "updates:unknown"))
        elif u["count"]:
            out.append(finding("fix", "updates", "%d security update%s waiting: %s." % (
                u["count"], "s are" if u["count"] != 1 else " is", few(u["names"])),
                [install_cmd(pkg)], "updates:%d FIX" % u["count"]))
        else:
            out.append(finding("ok", "updates", "No security updates are waiting.", share="updates:0"))
        age = u.get("age_days")
        if u["known"] and pkg == "apt" and age is None:
            out.append(finding("check", "lists", "Couldn't tell when this server last checked for updates, so the "
                                                 "updates list may be out of date.", [refresh_cmd(pkg)],
                               "lists:unknown"))
        elif u["known"] and age is not None and age > 7:
            out.append(finding("check", "lists", "This server last checked for updates %d days ago, so the updates "
                                                 "list may be out of date." % age,
                               [refresh_cmd(pkg)], "lists:%dd" % age))

    r = facts.get("reboot")
    if r and r.get("needed"):
        if r.get("why") == "kernel":
            text = ("A newer kernel (%s) is installed, but the server is still running %s. Restart to use it."
                    % (r["newest"], r["running"]))
        else:
            pk = r.get("pkgs") or []
            text = "Installed updates are waiting for a restart%s." % ((" (" + few(pk, 4) + ")") if pk else "")
        out.append(finding("check", "reboot", text, ["Restart at a quiet time: sudo reboot"], "reboot:yes"))
    elif r is not None:
        out.append(finding("ok", "reboot", "No restart is needed."))

    groups = {}
    for p in facts.get("php") or []:
        groups.setdefault((tuple(p["version"]), p["origin"]), []).append(p["path"])
    if not groups:
        out.append(finding("info", "php", "No PHP found in the usual places.", share="php:none"))
    for (ver, origin), paths in sorted(groups.items()):
        status, said = judge_php(ver, origin in ("distro", "panel"))
        if origin == "panel" and status != "ok":
            status = "check"
            said = ("runs the Plesk control panel itself, and isn't a release with the fix for %s. Plesk ships its "
                    "own builds of it, so install Plesk's updates, then check Plesk's security notice for these "
                    "flaws." % PHP_CVES)
        label = "%d.%d.%d" % ver
        where = paths[0] + (" and %d more" % (len(paths) - 1) if len(paths) > 1 else "")
        key = {"check": "php-confirm", "old": "php-old"}.get(status, "php")
        if status == "old":
            steps = ["Switch every site that uses PHP %d.%d to PHP 8.2 or newer (in Plesk or cPanel: each "
                     "domain's PHP settings), test the site, then remove PHP %d.%d." % (ver[0], ver[1], ver[0], ver[1])]
        else:
            steps = [] if status == "ok" else php_steps(paths[0], origin, facts)
        out.append(finding(status, key, "PHP %s (%s) %s" % (label, where, said), steps,
                           "php %s %s" % (label, status.upper())))

    out.extend(eval_tools(facts.get("tools") or [], pkg))

    s = facts.get("ssh")
    if s:
        restart = "sudo sshd -t && sudo systemctl %s" % ("restart ssh" if pkg == "apt" else "reload sshd")
        verify = "sudo sshd -T | grep -Ei '^(passwordauthentication|kbdinteractiveauthentication|permitrootlogin) '"
        if s["passwords"]:
            if s.get("exposed") is False:
                out.append(finding("info", "ssh-pass", "SSH accepts passwords, but only listens on this machine."))
            else:
                set_in = s.get("set_in")
                why = (" (switched on in %s)" % set_in) if set_in else " (OpenSSH's default: nothing switches it off)"
                first = "Set up an SSH key and log in with it first. Keep that window open while you test."
                done = "Log in from a NEW window before closing the old one. If it fails, undo the change in the old window."
                if s.get("dropin"):
                    lines = "PasswordAuthentication no\\nKbdInteractiveAuthentication no\\n"
                    if s.get("root") == "yes":
                        lines += "PermitRootLogin prohibit-password\\n"
                    steps = [first,
                             "Write a small settings file that SSH reads before any other (the first value it reads "
                             "wins, so this beats files like 50-cloud-init.conf):",
                             "printf '%s' | sudo tee /etc/ssh/sshd_config.d/00-vantax-keys-only.conf" % lines,
                             restart,
                             "Check it took (should say no, no and prohibit-password or without-password):",
                             verify, done,
                             "To undo, in the old window: sudo rm /etc/ssh/sshd_config.d/00-vantax-keys-only.conf "
                             "&& sudo systemctl %s" % ("restart ssh" if pkg == "apt" else "reload sshd")]
                    root_steps = ["Done by the same settings file in the step above."]
                else:
                    steps = [first,
                             "In /etc/ssh/sshd_config set: PasswordAuthentication no   and   "
                             "KbdInteractiveAuthentication no",
                             restart, "Check it took:", verify, done]
                    root_steps = ["In /etc/ssh/sshd_config set: PermitRootLogin prohibit-password   (keys only)",
                                  restart]
                out.append(finding("check", "ssh-pass", "SSH accepts password logins%s. Bots try passwords on "
                                                        "every server, all day." % why, steps, "ssh:passwords"))
                if s.get("root") == "yes":
                    out.append(finding("check", "ssh-root", "root can log in over SSH with a password.", root_steps,
                                       "ssh:root-password"))
        else:
            out.append(finding("ok", "ssh-pass", "SSH only accepts keys, not passwords."))

    for port in sorted(p for p in (facts.get("listeners") or []) if p in DB_PORTS):
        out.append(finding("check", "db", "%s is listening for connections from the network on port %d."
                           % (DB_PORTS.get(port, "A database"), port),
                           ["If nothing outside this server needs it, make it listen on 127.0.0.1 only, then restart it.",
                            "Otherwise make sure your firewall only lets trusted addresses reach port %d." % port],
                           "db:%d" % port))

    a = facts.get("auto")
    if a == "on":
        out.append(finding("ok", "auto", "Automatic security updates are on."))
    elif a == "download-only":
        out.append(finding("check", "auto", "Automatic updates download fixes but don't install them.",
                           ["Set apply_updates = yes in /etc/dnf/automatic.conf, or: "
                            "sudo systemctl enable --now dnf-automatic-install.timer"], "auto:download-only"))
    elif a == "off":
        steps = {"apt": ["sudo apt-get install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgrades"],
                 "dnf": ["sudo dnf install dnf-automatic && sudo systemctl enable --now dnf-automatic-install.timer"],
                 "yum": ["sudo yum install yum-cron && sudo systemctl enable --now yum-cron   "
                         "(and set apply_updates = yes in /etc/yum/yum-cron.conf)"]}.get(pkg, [])
        out.append(finding("check", "auto", "Automatic security updates are off, so every fix waits for someone to "
                                            "remember.", steps, "auto-updates:off"))

    wp = facts.get("wordpress") or []
    if wp:
        out.append(finding("info", "wp", "WordPress found on %d site%s (version%s %s). This check doesn't judge "
                                         "WordPress: keep core, plugins and themes updated from Dashboard > Updates."
                           % (len(wp), "s" if len(wp) != 1 else "", "s" if len(set(wp)) != 1 else "",
                              join(sorted(set(wp), key=natkey))), share="wordpress:%d" % len(wp)))

    if facts.get("errors"):
        out.append(finding("info", "errors", "Some checks couldn't run here: %s." % join(facts["errors"])))
    return out


# ---------------------------------------------------------------------------
# The report
# ---------------------------------------------------------------------------

LABEL = {"fix": "[FIX]  ", "old": "[OLD]  ", "check": "[CHECK]", "ok": "[OK]   ", "info": "[INFO] "}
COLOUR = {"fix": "1;31", "old": "35", "check": "33", "ok": "32", "info": "36"}
SECTIONS = [("fix", "FIX NOW"), ("old", "OUT OF SUPPORT: no more security fixes"), ("check", "CHECK"),
            ("ok", "OK"), ("info", "ALSO FOUND")]
TODO = [("lists", "Refresh the update list first"), ("xz", "Update xz now"), ("updates", "Install the waiting security updates"), ("php", "Update PHP"), ("php-old", "Move sites off old PHP versions"),
        ("openssh", "Update OpenSSH"), ("sudo", "Update sudo"), ("os", "Move to a supported operating system"),
        ("reboot", "Restart the server"), ("ssh-pass", "Switch SSH to keys only"),
        ("ssh-root", "Stop root logging in with a password"), ("db", "Close database ports to the internet"),
        ("auto", "Turn on automatic security updates"), ("php-confirm", "Confirm your PHP has the fix")]
NEEDS_ACTION = ("fix", "old", "check")


def paint(text, code, on):
    return "\033[%sm%s\033[0m" % (code, text) if on else text


def share_line(facts, findings):
    """One line, safe to paste into a message: versions and statuses only. No names, paths or addresses."""
    parts = ["vantax-check " + VERSION]
    parts += [f["share"] for f in findings if f.get("share")]
    web = [p for p in (facts.get("listeners") or []) if p in (80, 443)]
    parts.append("web:" + ((",".join(str(p) for p in web) or "none") if facts.get("listeners") is not None else "unknown"))
    parts.append("panel:" + (facts.get("panel") or "none"))
    parts.append("pkg:" + (facts.get("pkg") or "none"))
    parts.append("as-root:" + ("yes" if facts.get("root") else "no"))
    return " | ".join(parts)


def system_line(facts):
    o = facts.get("os")
    bits = [(o or {}).get("name") or "Unknown system"]
    if facts.get("panel"):
        bits.append({"plesk": "Plesk", "cpanel": "cPanel"}.get(facts["panel"], facts["panel"]))
    lis = facts.get("listeners")
    if lis is not None:
        web = [str(p) for p in lis if p in (80, 443)]
        bits.append(("serving the web on port%s %s" % ("s" if len(web) > 1 else "", " and ".join(web)))
                    if web else "not serving web pages on 80/443")
    if facts.get("running_php"):
        bits.append("PHP running: " + ", ".join(facts["running_php"]))
    return " - ".join(bits)


def report(facts, findings, colour=False):
    L = []
    add = L.append
    if facts.get("demo"):
        add(paint("EXAMPLE REPORT for a made-up server. Not your server.", "1;36", colour))
        add("")
    d = to_date(CHECKED)
    months = ("January February March April May June July August September October November December").split()
    add("Vantax server check %s - advisories and support dates checked %d %s %d"
        % (VERSION, d.day, months[d.month - 1], d.year))
    add("Reads this machine only. Changes nothing, sends nothing.")
    if not facts.get("root") and not facts.get("demo"):
        add("Tip: run it with sudo for a fuller check. It still changes nothing.")
    add("")
    add("System:  " + system_line(facts))
    counts = dict((k, sum(1 for f in findings if f["status"] == k)) for k in LABEL)
    add("Result:  %d to fix now, %d out of support, %d to check, %d OK"
        % (counts["fix"], counts["old"], counts["check"], counts["ok"]))
    for status, title in SECTIONS:
        items = [f for f in findings if f["status"] == status]
        if not items:
            continue
        add("")
        add(paint(title, COLOUR[status], colour))
        for f in items:
            wrapped = textwrap.wrap(f["text"], 92, break_on_hyphens=False, break_long_words=False) or [""]
            add("  %s %s" % (paint(LABEL[status], COLOUR[status], colour), wrapped[0]))
            for more in wrapped[1:]:
                add("          " + more)
    todo = []
    for key, title in TODO:
        steps = []
        for f in findings:
            if f["key"] == key and f["status"] in NEEDS_ACTION:
                for s in f["steps"]:
                    if s and s not in steps:
                        steps.append(s)
        if any(f["key"] == key and f["status"] in NEEDS_ACTION for f in findings):
            todo.append((title, steps))
    add("")
    if todo:
        add("WHAT TO DO, IN ORDER")
        for n, (title, steps) in enumerate(todo, 1):
            add("  %d. %s" % (n, title))
            for s in steps:
                if re.match(r"^(sudo|printf) ", s):  # commands stay on one line so they can be copied
                    add("       " + s)
                    continue
                for i, line in enumerate(textwrap.wrap(s, 88, break_on_hyphens=False, break_long_words=False) or [""]):
                    add(("       " if i == 0 else "         ") + line)
        add("  Then run this check again.")
    else:
        add("Nothing to do. Run it again after your next round of updates, or whenever there's news of a big flaw.")
    add("")
    add("Want a hand? Send this one line (no names, paths or passwords) to @VantaxFounder,")
    add("or see vantax-cybersecurity.com/check.html")
    add("  " + share_line(facts, findings))
    code = 1 if any(f["status"] in NEEDS_ACTION for f in findings) else 0
    return "\n".join(L), code


def demo():
    """A made-up server, judged by the real rules, so people can see what a report looks like."""
    return {
        "today": CHECKED, "demo": True, "root": True, "errors": [], "panel": "plesk", "pkg": "apt",
        "os": {"id": "debian", "version": "11", "name": "Debian GNU/Linux 11 (bullseye)", "like": "", "esm": False},
        "listeners": [22, 80, 443, 3306, 8443],
        "updates": {"known": True, "count": 9, "age_days": 1,
                    "names": ["libssl1.1", "openssh-server", "sudo", "linux-image-amd64", "libc6", "curl", "git",
                              "nginx", "tzdata"]},
        "reboot": {"needed": True, "why": "updates", "pkgs": ["linux-image-5.10.0-35-amd64"]},
        "php": [{"path": "/opt/plesk/php/8.3/bin/php", "version": [8, 3, 6], "origin": "upstream"},
                {"path": "/opt/plesk/php/7.4/bin/php", "version": [7, 4, 33], "origin": "upstream"},
                {"path": "/opt/plesk/php/8.5/bin/php", "version": [8, 5, 12], "origin": "upstream"}],
        "running_php": ["php-fpm"],
        "tools": [{"name": "openssh", "path": "/usr/sbin/sshd", "raw": "8.4p1", "origin": "distro"},
                  {"name": "sudo", "path": "/usr/bin/sudo", "raw": "1.9.5p2", "origin": "distro"},
                  {"name": "xz", "path": "/usr/bin/xz", "raw": "5.2.5", "origin": "distro"}],
        "ssh": {"passwords": True, "root": "yes", "ports": ["22"], "exposed": True, "source": "sshd -T"},
        "auto": "off", "wordpress": ["6.2.2", "6.6.1"],
    }


def main(argv):
    global ROOT
    if "--version" in argv:
        print(VERSION)
        return 0
    if os.name != "posix":
        print("This check runs on Linux servers (and Macs).", file=sys.stderr)
        return 2
    if "--root" in argv:  # for tests: look at a fake server in a folder
        i = argv.index("--root")
        if i + 1 >= len(argv):
            print("--root needs a folder", file=sys.stderr)
            return 2
        ROOT = argv[i + 1].rstrip("/")
    today = None
    if "--today" in argv:  # for tests: pretend it's another day (YYYY-MM-DD)
        i = argv.index("--today")
        today = argv[i + 1] if i + 1 < len(argv) else None
    facts = demo() if "--demo" in argv else gather(today)
    findings = evaluate(facts)
    text, code = report(facts, findings, colour=sys.stdout.isatty() and "NO_COLOR" not in os.environ)
    if "--json" in argv:
        print(json.dumps({"tool": "vantax-check", "version": VERSION, "checked": CHECKED, "demo": facts.get("demo"),
                          "facts": facts, "findings": findings, "share": share_line(facts, findings), "exit": code},
                         indent=2, sort_keys=True))
        return code
    enc = getattr(sys.stdout, "encoding", None) or "ascii"
    try:
        text.encode(enc)
    except (UnicodeEncodeError, LookupError):
        text = text.encode("ascii", "replace").decode("ascii")
    print(text)
    return code


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except KeyboardInterrupt:
        sys.exit(2)
