#!/usr/bin/env python3
"""minaki-tuner report | opt-in | license | uninstall | verify-license KEY | connect | disconnect | status | agent"""
import datetime, os, subprocess, sys

HERE = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, HERE)
import tunerlic
import report
import connect as C
import agent

ROOT = os.environ.get("MINAKI_ROOT", "")          # tests only
LICENSE = ROOT + "/etc/minaki-tuner/license"
OUT = ROOT + "/var/lib/minaki-tuner/report.md"
KEYS = {"live": HERE + "/keys/live.pem", "test": HERE + "/keys/test.pem"}

OPT_IN = """Minaki Tuner tunes a copy of this server, and only after you ask.
Give us a staging copy, not your production server: we work only on the address you give us and can't check that it is a copy.

What happens: your test is run, what the server really uses is recorded, unused software is removed and security
settings are applied in steps with a restart and your test after each, and undone if the test fails.

What we need from you:
  1. a staging copy (clone) of this server, reachable on SSH port 22 at a public IPv4 address;
  2. a non-root user there with password-less sudo;
  3. a test script that shows the server still does its job (exit 0), finishes within 300 s and holds no secrets.

Details and how to send it: https://minakilabs.com/minaki/docs/    Questions: support@minakilabs.com
Quote your subscription: %s

This command changed nothing."""


def die(msg):
    sys.exit("minaki-tuner: " + msg)


def current():
    try:
        return tunerlic.verify(open(LICENSE).read(), KEYS)
    except OSError:
        die("no license on this server (run with sudo, or install again with your key)")
    except tunerlic.Bad as e:
        die(str(e))


def run_cmd(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=900)
    return r.returncode, r.stdout, r.stderr


def version():
    return open(HERE + "/VERSION").read().strip()


def connected_host():
    return C.portal().replace("https://", "") if C.load() else None


def platform_ok():
    """Customers: Ubuntu 22.04 x86_64 only. The lab override is TUNER_UNSUPPORTED=1."""
    if os.environ.get("TUNER_UNSUPPORTED") == "1":
        return True
    rc, out, _ = run_cmd(["bash", HERE + "/detect.sh"])
    return rc == 0 and report.supported({"platform": out.strip()})


def license_key():
    """(key, why): the license key, only while it still verifies (offline). An expired key stops all sending."""
    try:
        k = open(LICENSE).read().strip()
        tunerlic.verify(k, KEYS)
        return k, ""
    except OSError:
        return None, "the license file is gone"
    except tunerlic.Bad as e:
        return None, "the license is no longer valid (%s); nothing more is sent" % e


def make_report():
    try:
        return report.generate(HERE, current(), version(), run_cmd, connected_host())
    except (RuntimeError, SystemExit):
        return None


def do_connect(args):
    lic = current()
    if not platform_ok():
        die("Minaki Tuner currently supports Ubuntu 22.04 LTS. Ubuntu 24.04 and Rocky Linux support is coming soon. Nothing was changed.")
    if C.load():
        die("this server is already connected (see: sudo minaki-tuner status)")
    if C.portal() != C.PORTAL_DEFAULT:
        print("LAB PORTAL %s (a test run, not the real service)" % C.portal())
    print(C.disclosure())
    print("Your license: %s %s. Disconnect any time: sudo minaki-tuner disconnect" % (lic["mode"], lic["sub"]))
    if "--yes" not in args:
        if not sys.stdin.isatty():
            die("not connected: run it in a terminal to confirm, or add --yes")
        if input("Connect this server? [y/N] ").strip().lower() not in ("y", "yes"):
            print("Not connected. Nothing was changed."); return
    C.UA = "minaki-tuner-client/" + version()
    got, err = C.enroll(open(LICENSE).read().strip(), version())
    if err:
        die("not connected: " + err)
    C.save({"client_id": got["client_id"], "server_id": got["server_id"], "portal": C.portal(), "lab": C.portal() != C.PORTAL_DEFAULT, "connected_at": int(__import__("time").time())})
    C.log("connected: server %s" % got["server_id"])
    ok = C.install_unit()
    print("Connected. The agent %s. Check: sudo minaki-tuner status" % ("is running" if ok else "could not be started (systemd): run `sudo systemctl status minaki-tuner-agent`"))


def do_disconnect():
    c = C.load()
    if not c:
        print("This server is not connected. Nothing to do."); return
    C.remove_unit()
    os.remove(C.CONF)
    C.log("disconnected")
    print("Disconnected. The agent is stopped and removed, and nothing more is sent. "
          "The portal has no disconnect call: this server stays in your dashboard, shown offline, until you remove it there.")


def do_status():
    c = C.load()
    if not c:
        print("Offline: this server is not connected. Nothing is sent anywhere."); return
    print("Connected to %s as server %s." % (c.get("portal", C.PORTAL_DEFAULT).replace("https://", ""), c.get("server_id", "?")))
    print(C.disclosure())
    tail = C.tail_log(3)
    print("Recent log:\n  " + "\n  ".join(tail) if tail else "No log lines yet.")


def main():
    verb = sys.argv[1] if len(sys.argv) > 1 else ""
    if verb == "verify-license" and len(sys.argv) == 3:
        try:
            print("license ok: %(mode)s %(sub)s" % tunerlic.verify(sys.argv[2], KEYS))
        except tunerlic.Bad as e:
            die(str(e))
        return
    if verb not in ("report", "opt-in", "license", "uninstall", "connect", "disconnect", "status", "agent"):
        die("use: report | opt-in | license | uninstall | connect | disconnect | status")
    if os.geteuid() != 0 and not os.environ.get("MINAKI_NOT_ROOT_OK"):
        die("run with sudo")
    if verb == "uninstall":
        if C.load():
            do_disconnect()
        for p in (LICENSE, OUT, ROOT + "/usr/local/bin/minaki-tuner"):
            if os.path.lexists(p):
                os.remove(p)
        subprocess.run(["rm", "-rf", "--", ROOT + "/opt/minaki-tuner"], check=True)
        print("Minaki Tuner client removed.")
        return
    C.UA = "minaki-tuner-client/" + version()        # every request names the client (the edge refuses a bare Python User-Agent)
    if verb == "connect":
        return do_connect(sys.argv[2:])
    if verb == "disconnect":
        return do_disconnect()
    if verb == "status":
        return do_status()
    if verb == "agent":
        return sys.exit(agent.run(version(), make_report, license_key))
    lic = current()
    if verb == "license":
        print("%s %s, valid to %s" % (lic["mode"], lic["sub"], datetime.datetime.fromtimestamp(lic["exp"], datetime.timezone.utc).date()))
    elif verb == "opt-in":
        print(OPT_IN % lic["sub"])
    else:
        try:
            text = report.generate(HERE, lic, version(), run_cmd, connected_host())
        except RuntimeError as e:
            die(str(e))
        os.makedirs(os.path.dirname(OUT), exist_ok=True)
        with open(OUT, "w") as f:
            f.write(text)
        user = os.environ.get("SUDO_USER")
        os.chmod(OUT, 0o640)
        if user and user != "root":                    # the person who ran it may read it without sudo
            import pwd
            u = pwd.getpwnam(user)
            os.chown(OUT, 0, u.pw_gid)
        print(text)
        print("Report saved: %s" % OUT)
        c = C.load()
        if c:
            C.UA = "minaki-tuner-client/" + version()
            code, _ = C.send_report(c, open(LICENSE).read().strip(), text)
            print("Report sent to %s." % C.portal().replace("https://", "") if code == 200 else
                  "Report NOT sent (status %s); it is saved here and the agent will send it later." % code)


main()
