#!/usr/bin/env python3
"""Install the IKM attendance package on ikm.kostricani.com from a WHM root terminal."""
import argparse
from contextlib import contextmanager
import fcntl
import hashlib
import http.client
import io
import json
from multiprocessing import Pipe
import os
from pathlib import Path
import pwd
import re
import stat
import subprocess
import sys
import tempfile
import urllib.error
import urllib.parse
import urllib.request
import zipfile

DOMAIN = "ikm.kostricani.com"
ZIP_NAME = "IKM-Attendance-cPanel.zip"
ZIP_BYTES = 68399
ZIP_SHA256 = "05912e8baa3304c4b4844e300cac4ce981f4f1eb2c17ec85bbcffb3340dd4972"
WHM = "/usr/local/cpanel/bin/whmapi1"
UAPI = "/usr/local/cpanel/bin/uapi"
RUNTIME_GRANTS = "SELECT,INSERT,UPDATE,DELETE"
ORIGINAL_LOAD = b"require_once dirname(__DIR__) . '/private/bootstrap.php';"
BEGIN = b"# BEGIN IKM attendance\n"
END = b"# END IKM attendance\n"
APACHE = BEGIN + b"""DirectoryIndex disabled
DirectoryIndex index.php
Options -Indexes
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(?:www[.])?ikm[.]kostricani[.]com(?::[0-9]+)?$ [NC]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://ikm.kostricani.com%{REQUEST_URI} [R=302,L,NE]
</IfModule>
""" + END


class InstallError(Exception):
    pass


def stop(message):
    raise InstallError(message)


def inside(path, parent):
    return path == parent or parent in path.parents


def check_path(path, home):
    if not inside(path, home) or path.resolve() != path:
        stop("Unexpected path or symbolic link: " + str(path))


def regular(path):
    if path.is_symlink() or (path.exists() and not path.is_file()):
        stop("Expected a regular file at " + str(path))


def same(path, data):
    regular(path)
    return path.is_file() and path.stat().st_size == len(data) and path.read_bytes() == data


def private_dir(path, mode=0o700):
    if path.is_symlink():
        stop("Unexpected directory link: " + str(path))
    try:
        path.mkdir(mode=mode)
    except FileExistsError:
        if not path.is_dir():
            stop("Expected a directory at " + str(path))
    else:
        path.chmod(mode)


def atomic_write(path, data, mode):
    fd, name = tempfile.mkstemp(prefix=".ikm-", dir=str(path.parent))
    try:
        with os.fdopen(fd, "wb") as file:
            file.write(data)
            file.flush()
            os.fchmod(file.fileno(), mode)
            os.fsync(file.fileno())
        os.replace(name, str(path))
    finally:
        if os.path.lexists(name):
            os.unlink(name)


def command(args, cwd=None):
    return subprocess.run(args, cwd=str(cwd) if cwd else None, stdin=subprocess.DEVNULL,
                          stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)


def result_data(process, label, whm=False):
    try:
        parsed = json.loads(process.stdout.decode())
        meta = parsed["metadata"] if whm else parsed["result"]
        status = meta.get("result" if whm else "status")
        if str(status) == "1" and process.returncode == 0:
            return parsed["data"] if whm else meta.get("data")
        reason = meta.get("reason") if whm else meta.get("errors")
        if isinstance(reason, list):
            reason = " ".join(str(x) for x in reason)
    except (ValueError, TypeError, AttributeError, KeyError):
        reason = None
    stop("{} failed. {}".format(label, str(reason or "Check the cPanel service and its command-line access.")[:600]))


def target():
    rows = result_data(command([WHM, "--output=json", "php_get_vhost_versions"]),
                       "WHM virtual host lookup", whm=True)["versions"]
    matches = [r for r in rows if str(r.get("vhost", "")).lower().rstrip(".") == DOMAIN]
    if len(matches) != 1:
        stop("WHM must list one virtual host for " + DOMAIN + ". Check cPanel > Domains.")
    row = matches[0]
    account = pwd.getpwnam(row["account"])
    home = Path(account.pw_dir).resolve()
    if account.pw_uid == 0 or home == Path("/") or not Path(row["documentroot"]).is_absolute():
        stop("Unexpected account or document root in WHM.")
    if row.get("homedir") and Path(row["homedir"]).resolve() != home:
        stop("WHM and the account database disagree about the home directory.")
    doc = Path(row["documentroot"]).resolve()
    if not doc.is_dir() or not inside(doc, home) or doc == home or str(row.get("is_suspended", 0)) == "1":
        stop("WHM's document root must be an existing directory in the active account's home.")
    app = home / "ikm-attendance"
    for other in rows:
        if not other.get("documentroot"):
            continue
        root = Path(other["documentroot"]).resolve()
        hostname = str(other.get("vhost", "")).lower().rstrip(".")
        if root == doc and hostname not in (DOMAIN, "www." + DOMAIN):
            stop("The document root is shared with {}. Give {} a dedicated document root in cPanel.".format(hostname, DOMAIN))
        for sub in (".install", "private", "database", "bin", "print", "IKM-cPanel.txt"):
            secret = (app / sub).resolve()
            if inside(secret, root) or inside(root, secret):
                stop("The private installation would overlap a web root: " + str(root))
    if (home / "public_html").resolve() == doc and str(row.get("main_domain")) == "0":
        stop("This subdomain shares the account's main public_html. Set a dedicated document root in cPanel.")
    version = row.get("version", "")
    if re.fullmatch(r"ea-php[0-9]{2,3}", version):
        php = "/opt/cpanel/{}/root/usr/bin/php".format(version)
    else:
        php = "/usr/local/bin/php"  # EasyApache resolves inherited versions from the working directory.
    if not os.access(php, os.X_OK):
        stop("PHP CLI for this virtual host was not found at " + php)
    return account, home, doc, app, php


def become_account(account, home):
    os.initgroups(account.pw_name, account.pw_gid)
    os.setgid(account.pw_gid)
    os.setuid(account.pw_uid)
    if os.getuid() != account.pw_uid or os.geteuid() == 0:
        stop("Could not switch to the cPanel account.")
    os.environ.clear()
    os.environ.update(HOME=str(home), USER=account.pw_name, LOGNAME=account.pw_name,
                      PATH="/usr/local/cpanel/bin:/usr/local/bin:/usr/bin:/bin", LANG="C")
    os.chdir(str(home))


def package(home, doc, state, supplied):
    candidates = [supplied, state / ZIP_NAME] if supplied else [
        home / "public_html" / ZIP_NAME, doc / ZIP_NAME, home / "public_html" / "ikm" / ZIP_NAME,
        home / "public_html" / DOMAIN / ZIP_NAME, state / ZIP_NAME, home / ZIP_NAME]
    for path in candidates:
        if not path.exists() and not path.is_symlink():
            continue
        if path == supplied:
            if path.resolve() != path:
                stop("Pass the original ZIP's real path: " + str(path.resolve()))
        else:
            check_path(path, home)
        regular(path)
        fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
        with os.fdopen(fd, "rb") as source:
            info = os.fstat(source.fileno())
            if not stat.S_ISREG(info.st_mode) or info.st_size != ZIP_BYTES:
                stop("The uploaded file does not match the original IKM ZIP: " + str(path))
            data = source.read(ZIP_BYTES + 1)
        if hashlib.sha256(data).hexdigest() != ZIP_SHA256:
            stop("The ZIP checksum does not match the original IKM-Attendance-cPanel.zip: " + str(path))
        with zipfile.ZipFile(io.BytesIO(data)) as z:
            files = {name.split("/", 1)[1]: z.read(name) for name in z.namelist() if not name.endswith("/")}
        return data, files, path
    stop("Could not find the ZIP. Checked:\n  " + "\n  ".join(map(str, candidates)) +
         "\nFor a renamed or nested upload, run again with --archive /absolute/path/to/file.zip.")


def php_literal(value):
    return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'"


def htaccess(path, original):
    regular(path)
    if path.is_file() and path.stat().st_size > 1024 * 1024:
        stop("Please review the existing " + str(path))
    old = path.read_bytes() if path.is_file() else b""
    if b"# BEGIN WordPress" in old:
        stop("This document root contains WordPress rules. Select a dedicated IKM document root in cPanel.")
    if BEGIN.strip() in old or END.strip() in old:
        if old.count(APACHE) != 1 or old.count(BEGIN.strip()) != 1 or old.count(END.strip()) != 1:
            stop("The existing IKM block was edited in " + str(path))
        return old, old
    prefix = b"" if old == original else old
    if prefix and not prefix.endswith(b"\n"):
        prefix += b"\n"
    return old, prefix + APACHE


def plan(home, doc, app, files):
    check_path(app, home)
    for filename in ("index.html", "index.htm", "default.html", "wp-config.php", "wp-admin"):
        path = doc / filename
        if path.exists() or path.is_symlink():
            stock = (filename in ("index.html", "index.htm", "default.html") and not path.is_symlink() and
                     path.is_file() and path.stat().st_size < 16384 and b"/cgi-sys/defaultwebpage.cgi" in path.read_bytes())
            if not stock:
                stop("An existing website uses {}. Give IKM a dedicated document root in cPanel.".format(path))
    entries = []
    old_ht, new_ht = htaccess(doc / ".htaccess", files["public/.htaccess"])
    for name, data in files.items():
        public = name.startswith("public/")
        path = doc / name[7:] if public else app / name
        check_path(path, home)
        regular(path)
        original = data
        if name == "public/load.php":
            bootstrap = php_literal(app / "private/bootstrap.php").encode()
            data = data.replace(ORIGINAL_LOAD, b"require_once " + bootstrap + b";")
        if name == "public/.htaccess":
            data = new_ht
        elif path.exists() and not same(path, data) and not (name == "public/load.php" and same(path, original)):
            stop("File differs from the IKM package; review it before installing: " + str(path))
        entries.append((name, path, data, public))
    for name in (".install", "private/config.php", "private/admin.hash"):
        check_path(app / name, home)
    for name in ("private/config.php", "private/admin.hash"):
        regular(app / name)
    return entries, old_ht


def put_entry(entry, root):
    name, path, data, public = entry
    # Walk only as far as the existing app or document root. Public assets need
    # traversable directories even though private installer files use umask 077.
    for parent in reversed(path.relative_to(root).parents):
        if str(parent) != ".":
            private_dir(root / parent, 0o755 if public else 0o700)
    if not same(path, data):
        atomic_write(path, data, 0o644 if public else (0o700 if name == "bin/set-admin-password" else 0o600))


PHP_PREFLIGHT = """
$missing = array_filter(['pdo_mysql','intl','mbstring','session'], function($ext) { return !extension_loaded($ext); });
if (PHP_VERSION_ID < 80200 || $missing) {
    fwrite(STDERR, 'PHP ' . PHP_VERSION . '; required: PHP 8.2+ with pdo_mysql, mbstring, intl, session. Missing: ' . implode(', ', $missing));
    exit(1);
}
echo 'PHP ', PHP_VERSION;
"""

PHP_DATABASE = r"""
try {
    require $argv[1] . '/private/bootstrap.php';
    $db = db();
    $version = (string)$db->query('SELECT VERSION()')->fetchColumn();
    $maria = stripos($version, 'MariaDB') !== false;
    $number = preg_replace('/^5\.5\.5-/', '', $version);
    if (!preg_match('/^\d+\.\d+\.\d+/', $number, $m) ||
        version_compare($m[0], $maria ? '10.2.1' : '8.0.16', '<')) {
        throw new RuntimeException('Incompatible database version ' . $version);
    }
    if ($argv[2] === 'import') {
        $sql = preg_replace('/^--[^\r\n]*/m', '', file_get_contents($argv[1] . '/database/setup.sql'));
        foreach (explode(';', $sql) as $statement) {
            if (trim($statement) !== '') { $db->exec($statement); }
        }
    }
    $tables = [
        'ikm_trainings' => 'id,title,training_date',
        'ikm_state' => 'id,active_training_id',
        'ikm_attendance' => 'id,training_id,first_name,last_name,email,email_key,checked_in_at,checked_out_at',
        'ikm_login_limits' => 'client_key,attempts,expires_at'
    ];
    $names = $db->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);
    if (array_diff(array_keys($tables), $names)) { exit(12); }
    foreach ($tables as $table => $columns) { $db->query("SELECT $columns FROM $table LIMIT 0"); }
    if ((int)$db->query('SELECT COUNT(*) FROM ikm_state WHERE id = 1')->fetchColumn() !== 1) { exit(12); }
    echo 'Verified all four tables and the attendance state.';
} catch (PDOException $e) {
    fwrite(STDERR, 'Database operation failed (SQLSTATE ' . $e->getCode() . ', driver ' . ($e->errorInfo[1] ?? '-') . ').');
    exit(1);
} catch (Throwable $e) {
    fwrite(STDERR, $e instanceof RuntimeException ? $e->getMessage() : get_class($e));
    exit(1);
}
"""


def php_run(php, doc, code, *args):
    return command([php, "-d", "display_errors=stderr", "-d", "log_errors=0", "-r", code, "--"] +
                   list(map(str, args)), doc)


def checked(p, label):
    if p.returncode:
        stop(label + ". " + p.stderr.decode(errors="replace").strip()[:600])
    return p.stdout.decode().strip()


def credentials(data):
    keys = ("database", "database_user", "database_user_password")
    return isinstance(data, dict) and all(isinstance(data.get(k), str) and data[k] for k in keys)


def mysql_error(value):
    if isinstance(value, list):
        value = " ".join(map(str, value))
    # The setup response can contain a one-time password. Only show diagnostic
    # text; never print a raw API response, a credentials record or a command.
    lines = []
    for line in str(value or "").splitlines():
        line = re.sub(r"\(using password:\s*(YES|NO)\)", "", line, flags=re.I)
        if not re.search(r"password|secret|token|authorization|credential|[{}]", line, re.I):
            lines.append(" ".join("".join(c for c in line if c.isprintable()).split()))
    return " ".join(lines)[:420] or "No further diagnostic text was returned."


class WhmMysql:
    """The root process only calls the MySQL operations needed by this account."""

    def __init__(self, owner, journal, allow_separate=False):
        self.owner = owner
        self.journal = journal
        self.allow_separate = allow_separate
        self.transport = None
        self.pair = None

    def call(self, operation, literal_commas=False, **params):
        whm = self.transport != "uapi"
        if whm:
            args = [WHM, "--output=json", "uapi_cpanel", "cpanel.user=" + self.owner,
                    "cpanel.module=Mysql", "cpanel.function=" + operation]
        else:
            args = [UAPI, "--output=json", "--user=" + self.owner, "Mysql", operation]
        args.extend(key + "=" + urllib.parse.quote(value, safe="," if literal_commas else "") for key, value in params.items())
        proc = command(args, "/")
        try:
            data = json.loads(proc.stdout.decode())
            if whm and str(data["metadata"]["result"]) != "1":
                stop("WHM Mysql/{}: ".format(operation) +
                     mysql_error(data["metadata"].get("reason") or proc.stderr.decode(errors="replace")))
            result = data["data"]["uapi"] if whm else data["result"]
            if str(result["status"]) != "1" or proc.returncode:
                stop("cPanel Mysql/{} (exit {}): {}".format(operation, proc.returncode,
                     mysql_error(result.get("errors") or proc.stderr.decode(errors="replace"))))
            return result["data"]
        except (ValueError, TypeError, KeyError, AttributeError):
            stop("{} Mysql/{} returned no usable result (exit {}). {}".format(
                 "WHM" if whm else "cPanel", operation, proc.returncode, mysql_error(proc.stderr.decode(errors="replace"))))

    def inventory(self):
        # Switching routes is safe here: both operations only read inventory.
        errors = []
        for route in ([self.transport] if self.transport else ["whm", "uapi"]):
            self.transport = route
            try:
                databases = self.call("list_databases")
                users = self.call("list_users")
                for rows, key in ((databases, "database"), (users, "user")):
                    if not isinstance(rows, list) or not all(isinstance(r, dict) and isinstance(r.get(key), str) for r in rows):
                        stop("Unrecognized {} list returned by {}.".format(key, route))
                return databases, users
            except (InstallError, OSError, subprocess.TimeoutExpired) as err:
                errors.append(str(err))
        stop("Cannot read this account's MySQL inventory. " + " / ".join(errors))

    def ikm_name(self, name):
        name = name.lower()
        parts = (self.owner.lower(), self.owner[:8].lower(), self.owner[:16].lower())
        if name in parts:
            return False  # Some versions include the account's main MySQL login.
        prefix, sep, suffix = name.partition("_")
        if sep and prefix in parts:
            return suffix.startswith("ikm")
        return name.startswith("ikm") or (bool(sep) and suffix.startswith("ikm"))

    def journal_data(self):
        if not self.journal.exists():
            return None
        regular(self.journal)
        try:
            data = json.loads(self.journal.read_text())
        except ValueError:
            stop("The root-owned IKM credentials journal is unreadable. Inspect its permissions and restore its backup.")
        if not credentials(data):
            stop("The root-owned IKM credentials journal is incomplete.")
        return data

    def provision(self):
        databases, users = self.inventory()
        db_names = {r["database"] for r in databases}
        user_names = {r["user"] for r in users}
        saved = self.journal_data()
        if saved:
            self.pair = (saved["database"], saved["database_user"])
            if self.pair[0] not in db_names or self.pair[1] not in user_names:
                stop("The database or user in the saved IKM credentials is absent from this cPanel account. Check My Databases.")
            return saved
        pending = self.journal.with_suffix(".pending.json")
        regular(pending)
        if pending.exists():
            try:
                before = json.loads(pending.read_text())
                appeared = sorted((db_names - set(before["databases"])) | (user_names - set(before["users"])))
            except (ValueError, TypeError, KeyError):
                stop("The root-owned inventory saved before the last database request is unreadable. Check the WHM MySQL inventory before retrying.")
            if appeared:
                stop("Database resources appeared after the previous provisioning request: " + ", ".join(appeared) +
                     ". Check their ownership and credentials in WHM before continuing.")
        else:
            possible = sorted(n for n in db_names | user_names if self.ikm_name(n))
            if possible and not self.allow_separate:
                stop("Possible existing IKM database or user: " + ", ".join(possible) +
                     ". No database was created. If these must stay separate from this installation, rerun with --separate-database.")
            before = {"databases": sorted(db_names), "users": sorted(user_names)}
            atomic_write(pending, json.dumps(before).encode(), 0o600)
        saved = self.call("setup_db_and_user", prefix="ikm")
        if not credentials(saved):
            stop("cPanel did not return the generated database credentials. The next run will check the inventory again.")
        atomic_write(self.journal, json.dumps(saved).encode(), 0o600)
        pending.unlink()
        self.pair = (saved["database"], saved["database_user"])
        return saved

    def permissions(self, mode, name, user):
        if not all(isinstance(n, str) and re.fullmatch(r"[a-zA-Z0-9_-]{1,64}", n) for n in (name, user)):
            stop("Unexpected IKM database identifier.")
        if self.pair is None:
            databases, users = self.inventory()
            saved = self.journal_data()
            if saved:
                self.pair = (saved["database"], saved["database_user"])
            else:
                # A complete receipt from the first installer predates the root journal.
                # Confirm both objects and their association in the owner's inventory.
                linked = any(r["database"] == name and user in (r.get("users") or []) for r in databases)
                linked = linked or any(r["user"] == user and name in (r.get("databases") or []) for r in users)
                if not linked or not self.ikm_name(name):
                    stop("The saved IKM database and user could not be matched to this account in cPanel.")
                self.pair = (name, user)
        if self.pair != (name, user):
            stop("The requested database and user do not match the saved IKM installation.")
        grants = RUNTIME_GRANTS if mode == "runtime" else RUNTIME_GRANTS + ",CREATE,REFERENCES"
        params = {"database": name, "user": user, "privileges": grants}
        try:
            self.call("set_privileges_on_database", **params)
        except InstallError as err:
            if not re.search(r"%2c|invalid privilege|privilege.{0,80}(?:invalid|not valid|unrecognized)", str(err), re.I):
                raise
            self.call("set_privileges_on_database", literal_commas=True, **params)


@contextmanager
def mysql_channel(owner, journal, allow_separate=False):
    # The terminal process drops privileges. The small helper keeps its original
    # identity and the fixed WHM account. Only JSON crosses this inherited pipe.
    client, server = Pipe()
    pid = os.fork()
    if pid == 0:
        client.close()
        api = WhmMysql(owner, journal, allow_separate)
        try:
            while True:
                try:
                    payload = server.recv_bytes(4096)
                except EOFError:
                    break
                try:
                    request = json.loads(payload.decode())
                    if request == ["provision"]:
                        result = api.provision()
                    elif isinstance(request, list) and len(request) == 3 and request[0] in ("runtime", "schema"):
                        result = api.permissions(*request)
                    else:
                        stop("Unknown IKM database operation.")
                    answer = {"data": result}
                except (InstallError, OSError, ValueError, TypeError, subprocess.TimeoutExpired) as err:
                    answer = {"error": str(err) if isinstance(err, InstallError) else
                              "Local database helper failed ({}). Check the cPanel service and rerun.".format(type(err).__name__)}
                server.send_bytes(json.dumps(answer).encode())
        finally:
            server.close()
            os._exit(0)
    server.close()

    def request(*parts):
        try:
            client.send_bytes(json.dumps(parts).encode())
            response = json.loads(client.recv_bytes(65536).decode())
        except (EOFError, OSError, ValueError):
            stop("The root WHM database helper closed before it returned a result.")
        if "error" in response:
            stop(response["error"])
        return response["data"]

    try:
        yield request
    finally:
        client.close()
        os.waitpid(pid, 0)


def database_receipt(mysql, state, has_config):
    path = state / "database-result.json"
    regular(path)
    prior = path.read_bytes() if path.exists() else b""
    try:
        reply = json.loads(prior.decode())["result"]
        if str(reply["status"]) == "1" and credentials(reply.get("data")):
            return reply["data"]
    except (ValueError, TypeError, KeyError, AttributeError):
        pass
    if has_config:
        return None  # First try the credentials already in the private application config.
    if path.exists():
        print("The previous database result is incomplete. Checking this account in WHM.", flush=True)
    db = mysql("provision")
    if prior:
        backup = state / "database-result.before-repair.json"
        if not backup.exists():
            atomic_write(backup, prior, 0o600)
    atomic_write(path, json.dumps({"result": {"status": 1, "data": db}}).encode(), 0o600)
    return db


def config_bytes(db):
    host = db.get("hostname") or "localhost"
    port = int(db.get("port") or 3306)
    if not 1 <= port <= 65535 or any(c in str(host) for c in ";\r\n\0"):
        stop("cPanel returned an invalid database address.")
    values = [("db_host", php_literal(host)), ("db_port", str(port)), ("db_name", php_literal(db["database"])),
              ("db_user", php_literal(db["database_user"])), ("db_password", php_literal(db["database_user_password"]))]
    return ("<?php\ndeclare(strict_types=1);\nreturn [\n" +
            "".join("    '{}' => {},\n".format(k, v) for k, v in values) + "];\n").encode()


def setup_database(mysql, state, app, php, doc):
    config = app / "private/config.php"
    db = database_receipt(mysql, state, config.exists())
    if db:
        content = config_bytes(db)
        if not config.exists():
            atomic_write(config, content, 0o600)
        elif not same(config, content):
            stop("Existing private/config.php differs from the saved database receipt. Review it before retrying.")
    config.chmod(0o600)
    if db:
        mysql("runtime", db["database"], db["database_user"])
    probe = php_run(php, doc, PHP_DATABASE, app, "verify")
    if probe.returncode == 12:
        if not db:
            stop("The existing config.php points to an incomplete schema. Import the bundled database/setup.sql into that database, then rerun.")
        try:
            mysql("schema", db["database"], db["database_user"])
            probe = php_run(php, doc, PHP_DATABASE, app, "import")
        finally:
            mysql("runtime", db["database"], db["database_user"])
        checked(probe, "The IKM database did not pass its schema check")
        probe = php_run(php, doc, PHP_DATABASE, app, "verify")
    print(checked(probe, "Verification with the application credentials failed"), flush=True)


def admin_password(app, php, doc):
    path = app / "private/admin.hash"
    if not path.exists():
        if not sys.stdin.isatty():
            stop("Run from an interactive WHM or SSH terminal to set the IKM admin password.")
        print("Set the IKM admin password (12–72 bytes). Type it twice; the terminal hides both entries.", flush=True)
        env = dict(os.environ, PHP_BIN=php)
        if subprocess.call(["/bin/bash", str(app / "bin/set-admin-password")], cwd=str(doc), env=env):
            stop("The password was not saved. Run the installer again to retry.")
    path.chmod(0o600)
    code = "require $argv[1].'/private/auth.php'; if (admin_hash() === '') { exit(1); }"
    checked(php_run(php, doc, code, app), "The saved admin password hash is invalid")


def store_package(home, doc, state, raw, source):
    saved = state / ZIP_NAME
    if not same(saved, raw):
        if saved.exists():
            stop("A different archive already occupies " + str(saved))
        atomic_write(saved, raw, 0o600)
    for path in {source, home / "public_html" / ZIP_NAME, doc / ZIP_NAME}:
        if path != saved and (inside(path, doc) or inside(path, home / "public_html")):
            try:
                if not path.is_symlink() and path.is_file() and same(path, raw):
                    path.unlink()
            except PermissionError:
                print("Private ZIP saved. The cPanel account could not remove the uploaded copy at " + str(path), file=sys.stderr)


class SameSiteRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        origin = urllib.parse.urlsplit(newurl)
        if origin.scheme != "https" or origin.netloc.lower() != DOMAIN:
            raise ValueError("Redirected away from the IKM HTTPS domain")
        return super().redirect_request(req, fp, code, msg, headers, newurl)


def https_checks():
    opener = urllib.request.build_opener(SameSiteRedirect())
    tests = [("/", "<title>Regjistro prezencën · IKM</title>"), ("/admin/", "<title>Hyrja e administratorit · IKM</title>")]
    passed = True
    for route, marker in tests:
        url = "https://" + DOMAIN + route
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "IKM-Install/1", "Cache-Control": "no-cache"})
            with opener.open(req, timeout=12) as page:
                body = page.read(300000)
                if page.getcode() != 200 or marker.encode() not in body or b"<?php" in body:
                    raise ValueError("The expected IKM page was not returned")
            print("HTTPS OK  " + url)
        except (OSError, ValueError, http.client.HTTPException) as err:
            print("HTTPS check pending  {}  ({})".format(url, err), file=sys.stderr)
            passed = False
    return passed


def install(mysql, home, doc, app, php, raw, files, source, dry):
    state = app / ".install"
    plan(home, doc, app, files)
    if not os.access(doc, os.W_OK | os.X_OK):
        stop("The cPanel account needs write access to the domain's document root: " + str(doc))
    print("Archive verified. " + checked(php_run(php, doc, PHP_PREFLIGHT), "PHP preflight failed"), flush=True)
    if dry:
        print("Preflight passed. Database provisioning and HTTPS are checked during the install.")
        return 0
    private_dir(app, 0o711 if inside(doc, app) else 0o700)
    private_dir(state)
    lockpath = state / "install.lock"
    regular(lockpath)
    with lockpath.open("a+b") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            stop("Another IKM installation is running.")
        entries, old_ht = plan(home, doc, app, files)
        store_package(home, doc, state, raw, source)
        for entry in entries:
            if not entry[3]:
                put_entry(entry, app)
        admin_password(app, php, doc)
        setup_database(mysql, state, app, php, doc)

        # Recheck conflicts after the interactive password step. Expose the
        # entry points only after their dependencies and the database are ready.
        entries, old_ht = plan(home, doc, app, files)
        backup = state / "htaccess.before-ikm"
        if old_ht and BEGIN not in old_ht and not backup.exists():
            atomic_write(backup, old_ht, 0o600)
        public = [entry for entry in entries if entry[3]]
        public.sort(key=lambda e: (e[0].endswith("/index.php"), e[0] == "public/index.php"))
        for entry in public:
            put_entry(entry, doc)
    print("Installed IKM files and database. Checking the two HTTPS pages.", flush=True)
    if https_checks():
        print("IKM is ready. Sign in at https://" + DOMAIN + "/admin/ and open your first training.")
        return 0
    print("Files and database are installed. Check DNS, SSL and the domain's PHP handler, then rerun the same command.", file=sys.stderr)
    return 2


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--archive", type=Path, help="path to the original ZIP if uploaded elsewhere or renamed")
    parser.add_argument("--check", action="store_true", help="check the target, archive, conflicts and PHP without installing")
    parser.add_argument("--separate-database", action="store_true", help="explicitly create a separate IKM database when unverified IKM-named resources exist")
    args = parser.parse_args()
    if os.geteuid() != 0:
        stop("Start in the WHM Terminal or SSH as root.")
    os.umask(0o077)
    account, home, doc, app, php = target()
    supplied = args.archive.absolute() if args.archive else None
    print("Domain: {}\nAccount: {}\nDocument root: {}\nPrivate directory: {}".format(
          DOMAIN, account.pw_name, doc, app / "private"), flush=True)
    raw, files, source = package(home, doc, app / ".install", supplied)
    journal = Path("/root") / (".ikm-db-" + DOMAIN + "-" + str(account.pw_uid) + ".json")
    with mysql_channel(account.pw_name, journal, args.separate_database) as mysql:
        become_account(account, home)
        return install(mysql, home, doc, app, php, raw, files, source, args.check)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except subprocess.TimeoutExpired as exc:
        print("Timed out waiting for {}. Rerun the installer to resume.".format(Path(exc.cmd[0]).name), file=sys.stderr)
        sys.exit(1)
    except (InstallError, OSError, KeyError, ValueError, zipfile.BadZipFile) as exc:
        print("IKM installation stopped. " + str(exc), file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        print("\nInstallation interrupted. Rerun the same installer to resume.", file=sys.stderr)
        sys.exit(130)
