#!/usr/bin/python3
"""Link an appliance to TurnKey Hub services.

Launch registration and readiness use the installed integration package.
Mail and DNS configuration share this helper across all appliance apps.
"""
import sys

# The public command opens setup; subcommands remain available to services.
if __name__ == "__main__" and len(sys.argv) == 1:
    import os
    os.execv("/usr/lib/inithooks/bin/hubservices.py", ["hubservices.py", "--setup"])

# A partial package must remain probeable without opening saved credentials,
# repairing mail configuration, creating locks or writing Python bytecode.
if __name__ == "__main__" and len(sys.argv) > 1 and sys.argv[1] in ("capabilities", "register"):
    sys.dont_write_bytecode = True
    try:
        if sys.argv[1] == "capabilities":
            from libinithooks.hub_capabilities import main
        else:
            from libinithooks.hub_launch import main
        sys.exit(main(sys.argv[2:]))
    except Exception:
        if sys.argv[1] == "capabilities":
            import json
            print(json.dumps({"protocol": "hub-services-v1", "ready": False,
                              "missing": ["libinithooks.hub_capabilities"]}))
        else:
            print("Hub registration could not finish. Check the installed Hub packages and retry.", file=sys.stderr)
        sys.exit(1)

import argparse
import contextlib
import email.message
import fcntl
import hashlib
import ipaddress
import json
import math
import os
from pathlib import Path
import re
import secrets
import smtplib
import socket
import ssl
import stat
import subprocess
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request

try:
    from libinithooks import hub_runtime
    RUNTIME = hub_runtime if hub_runtime.enabled() else None
except ImportError:
    RUNTIME = None

TURNKEY_VERSION = Path("/etc/turnkey_version")
BUILD_TAGS = Path("/etc/apt/apt.conf.d/01turnkey")
ONBOARDING_STATE = Path("/var/lib/turnkey-onboarding/state.json")
HUB_EMAIL_CACHE = Path("/var/lib/inithooks/cache/HUB_ACCOUNT_EMAIL")
HUB = "https://hub.turnkeylinux.org"
STATE_DIR = Path("/var/lib/turnkey-hub")
POSTFIX_DIR = Path("/etc/postfix")
SYSTEMD_DIR = Path("/etc/systemd/system")
BACKUP_DIR = Path("/var/lib/tklbam")
BACKUP_CRON = Path("/etc/cron.daily/tklbam-backup")
BACKUP_CRON_REFERENCE = Path("/usr/share/tklbam/contrib/cron.sh")
BACKUP_CRON_CAPABILITY = b"# Supports Hub-managed daily backups (v1)."
BACKUP_CRON_CHANGED = ("This server’s daily backup job changed during setup. "
                       "Start a new connection to use its current backup settings.")
HUBDNS_DIR = Path("/var/lib/hubdns")
HELPER = "/usr/lib/inithooks/bin/turnkey-hub"
MAX_JSON = 65536
DEVICE_CODE = re.compile(r"^[A-Za-z0-9_-]{32,256}$")
SERVICE_SECRET = re.compile(r"^[A-Za-z0-9_-]{43}$")
BACKUP_TOKEN = re.compile(r"tklbam2\.([0-9a-f]{32})\.[A-Za-z0-9_-]{43}")
DAILY_BACKUP_MARKER = re.compile(r"([0-9a-f]{32}) (local|managed)")
DEVICE_ID = re.compile(r"^[a-f0-9]{32}$")
ENROLLMENT_TOKEN = re.compile(r"^[a-f0-9]{32}\.[a-f0-9]{64}$")
HOST = re.compile(r"^(?=.{1,253}$)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$", re.I)
ADDRESS = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+$")
# Optional consumers can be installed after pairing. Backup v2 also requires
# the stock TKLBAM scheduler when the appliance starts the connection.
SUPPORTED_SERVICES = {"email": [1], "dns": [1], "backup": [1, 2]}
SERVICE_FIELDS = {"email": ("enabled", "status", "grant_id", "domain", "sender"),
                  "dns": ("enabled", "status", "hostname", "update_uri"),
                  "backup": ("requested", "status", "action_url")}
ERRORS = {
    "stale_configuration": "The Hub settings changed. Synchronize again.",
    "invalid_credentials": "This Hub connection is no longer authorized. Link it again.",
    "expired": "This connection request expired. Start a new connection.",
    "denied": "The connection was not approved. Start again when ready.",
    "invalid_token": "This connection request is invalid or expired. Start a new connection.",
    "revoked": "This server's connection was revoked. Connect it again in the Hub.",
    "not_authorized": "This server is no longer authorized. Check its connection in the Hub.",
    "rate_limited": "The Hub is busy. Please wait and try again.",
}


def appliance_description():
    """The app, TurnKey release and build type of this appliance; empty if unknown.

    Sent when linking so the Hub can show which machine is being approved. The
    app and release come from /etc/turnkey_version (turnkey-wordpress-18.0-
    bookworm-amd64). The build type is the tag the build task left in the apt
    configuration (proxmox, vm, ec2, docker...); an untagged build is an ISO.
    """
    try:
        match = re.fullmatch(r"turnkey-(.+)-(\d[^-]*)-([^-]+)-([^-]+)", TURNKEY_VERSION.read_text().strip())
    except OSError:
        return {}
    if not match:
        return {}
    description = {"app": match[1][:40], "release": match[2][:16]}
    try:
        tags = re.search(r"\(([^)]+)\)", BUILD_TAGS.read_text())
    except OSError:
        tags = None
    if tags:
        description["build_target"] = " ".join(tags[1].split()[1:])[:40] or "iso"
    return description


class Error(Exception):
    def __init__(self, message, code="failed", retryable=False):
        super().__init__(message)
        self.code = code
        self.retryable = retryable


def atomic(path, content, mode=0o600):
    path = Path(path)
    fd, temporary = tempfile.mkstemp(prefix="." + path.name + "-", dir=str(path.parent))
    try:
        os.fchmod(fd, mode)
        with os.fdopen(fd, "wb") as stream:
            stream.write(content.encode() if isinstance(content, str) else content)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def stock_backup_cron_mode():
    try:
        if BACKUP_CRON.is_symlink() or not BACKUP_CRON.is_file():
            return None
        reference = BACKUP_CRON_REFERENCE.read_bytes()
        if BACKUP_CRON_CAPABILITY in reference.splitlines() and BACKUP_CRON.read_bytes() == reference:
            return stat.S_IMODE(BACKUP_CRON.stat().st_mode)
    except OSError:
        pass
    return None


def eligible_backup_cron_mode():
    mode = stock_backup_cron_mode()
    if mode is None:
        return None
    for frequency in ("hourly", "weekly"):
        alternate = BACKUP_CRON.parent.with_name("cron." + frequency) / BACKUP_CRON.name
        if alternate.is_file() and os.access(alternate, os.X_OK):
            return None
    return mode


def forget_backup_auth(device_id=None):
    token = BACKUP_TOKEN.fullmatch(backup_file("sub_apikey") or "")
    if token and (device_id is None or token.group(1) == device_id):
        (BACKUP_DIR / "credentials").unlink(missing_ok=True)
        (BACKUP_DIR / "sub_apikey").unlink(missing_ok=True)


def backup_file(name):
    try:
        return (BACKUP_DIR / name).read_text().rstrip()
    except FileNotFoundError:
        return None


def daily_backup_marker():
    content = backup_file("hub-managed-daily")
    if content is None:
        return None
    previous = DAILY_BACKUP_MARKER.fullmatch(content)
    if not previous:
        raise Error("The daily backup schedule marker is invalid. Check the TKLBAM schedule on this server.")
    return previous.groups()


def remove_daily_backup():
    previous = daily_backup_marker()
    if previous and previous[1] == "managed":
        stock_mode = stock_backup_cron_mode()
        if stock_mode is not None and stock_mode & stat.S_IXUSR:
            BACKUP_CRON.chmod(stock_mode & ~stat.S_IXUSR)
    # A locally owned executable falls back to the legacy invocation when the
    # marker is removed. Retire credentials for both pending and ready devices.
    ready = backup_file("hub-daily-initialized")
    if ready and DEVICE_ID.fullmatch(ready):
        forget_backup_auth(ready)
    if previous and previous[0] != ready:
        forget_backup_auth(previous[0])
    (BACKUP_DIR / "hub-daily-initialized").unlink(missing_ok=True)
    (BACKUP_DIR / "hub-managed-daily").unlink(missing_ok=True)


def run(command, data=None, timeout=30):
    try:
        result = subprocess.run(command, input=data, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired):
        raise Error("A required system command could not finish. Check the service and try again.", retryable=True)
    if result.returncode:
        # Command stderr may include SMTP or Postfix credential data.
        raise Error("The mail service could not apply these settings. Existing settings were restored.", retryable=True)
    return result.stdout


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def request(route, payload, namespace="appmail", *, timeout=15):
    """Only post credentials to the fixed, certificate-verified Hub origin."""
    if namespace not in ("appmail", "connections") or not re.fullmatch(r"[a-z/]+", route):
        raise Error("Invalid Hub operation.")
    body = json.dumps(payload).encode()
    req = urllib.request.Request("%s/api/%s/%s" % (HUB, namespace, route), data=body,
                                 headers={"Content-Type": "application/json", "Accept": "application/json"})
    opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=ssl.create_default_context()))
    try:
        with opener.open(req, timeout=timeout) as response:
            raw = response.read(MAX_JSON + 1)
    except urllib.error.HTTPError as exc:
        code = "unavailable"
        try:
            detail = json.loads(exc.read(MAX_JSON + 1))
            code = detail.get("error", code)
        except (ValueError, AttributeError):
            pass
        retryable = exc.code in (408, 429) or exc.code >= 500
        raise Error(ERRORS.get(code, "The Hub could not complete this request. Check the connection in the Hub and try again."),
                    code=code if code in ERRORS else "unavailable", retryable=retryable)
    except (OSError, urllib.error.URLError):
        raise Error("The Hub is temporarily unavailable. Your connection will be retried.", code="unavailable", retryable=True)
    try:
        value = json.loads(raw)
        if len(raw) > MAX_JSON or not isinstance(value, dict):
            raise ValueError()
        return value
    except (ValueError, UnicodeError):
        raise Error("The Hub returned an invalid response. Please try again.", retryable=True)


def checked_config(value, password, custom=False):
    try:
        smtp = value["smtp"]
        host = smtp["host"].lower()
        port = int(smtp["port"])
        username = smtp["username"]
        if not HOST.fullmatch(host) or ".." in host or not 1 <= port <= 65535:
            raise ValueError()
        if not isinstance(username, str) or not username or any(c.isspace() or ord(c) < 32 for c in username) or ":" in username:
            raise ValueError()
        if not isinstance(password, str) or not password or any(ord(c) < 32 or ord(c) == 127 for c in password):
            raise ValueError()
        result = {"smtp": {"host": host, "port": port, "username": username}, "password": password,
                  "mode": "custom" if custom else "hub", "status": value.get("status", "ready")}
        if not custom:
            domain = value["domain"].lower()
            sender = value["sender"]
            dns = value.get("dyndns")
            if value.get("version") != 1 or result["status"] not in ("ready", "pending"):
                raise ValueError()
            if not HOST.fullmatch(domain) or not ADDRESS.fullmatch(sender) or sender.rsplit("@", 1)[1] != domain:
                raise ValueError()
            if dns and (not HOST.fullmatch(dns["hostname"]) or not dns["hostname"].endswith(".tklapp.com")
                        or dns["update_uri"] != HUB + "/api/appmail/dns/update"):
                raise ValueError()
            result.update(domain=domain, sender=sender, device_id=value["device_id"], dyndns=dns)
        return result
    except (KeyError, ValueError, TypeError, AttributeError):
        raise Error("The mail settings are incomplete or invalid. Existing settings were kept.")


def connection_service(name, entry, device_id):
    """Keep supported settings separate from the secrets they arrived with."""
    if not isinstance(entry, dict) or type(entry.get("version")) is not int:
        raise Error("The Hub returned invalid service settings.")
    version = entry["version"]
    if version not in SUPPORTED_SERVICES[name]:
        return {}, None
    public = {"version": version}
    for key in SERVICE_FIELDS[name]:
        if key not in entry:
            continue
        kind = bool if key in ("enabled", "requested") else str
        if type(entry[key]) is not kind:
            raise Error("The Hub returned invalid service settings.")
        public[key] = entry[key]
    if name == "backup" and version == 2 and (
            "requested" not in public or public.get("status") not in (
                "disabled", "active", "secret_required", "setup_required", "migration_required")):
        raise Error("The Hub returned invalid backup settings.")
    secret = entry.get("credential")
    if name == "email" and public.get("status") in ("active", "pending_verification"):
        if (not public.get("enabled") or not DEVICE_ID.fullmatch(public.get("grant_id", "")) or
                not isinstance(secret, str) or not SERVICE_SECRET.fullmatch(secret)):
            raise Error("The Hub returned an invalid email credential.")
        config = hub_mail_config(device_id, dict(public, smtp=entry.get("smtp")), secret)
        public["smtp"] = config["smtp"]
    elif name == "dns" and public.get("enabled"):
        hostname = public.get("hostname", "")
        if (not HOST.fullmatch(hostname) or not hostname.endswith(".tklapp.com") or
                public.get("update_uri") != HUB + "/api/appmail/dns/update"):
            raise Error("The Hub returned invalid DNS settings.")
        secret = scoped_secret(secret, "hubdns2", device_id)
    elif name == "backup" and public.get("status") == "active":
        if not public.get("requested"):
            raise Error("The Hub returned invalid backup settings.")
        secret = scoped_secret(secret, "tklbam2", device_id)
    else:
        secret = None
    return public, secret


def scoped_secret(token, scope, device_id):
    prefix = "%s.%s." % (scope, device_id)
    if not isinstance(token, str) or not token.startswith(prefix) or not SERVICE_SECRET.fullmatch(token[len(prefix):]):
        raise Error("The Hub returned an invalid service credential.")
    return token[len(prefix):]


def hub_mail_config(device_id, mail, secret):
    envelope = dict(version=1, device_id=device_id, smtp=mail.get("smtp"),
                    domain=mail.get("domain"), sender=mail.get("sender"),
                    status="ready" if mail.get("status") == "active" else "pending")
    return checked_config(envelope, secret)


def remember_account_email(email):
    if isinstance(email, str) and len(email) <= 254 and ADDRESS.fullmatch(email):
        HUB_EMAIL_CACHE.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        atomic(HUB_EMAIL_CACHE, email + "\n")
        return email
    return ""


def smtp_check(config):
    smtp = config["smtp"]
    try:
        context = ssl.create_default_context()
        if smtp["port"] == 465:
            client = smtplib.SMTP_SSL(smtp["host"], smtp["port"], timeout=10, context=context)
        else:
            client = smtplib.SMTP(smtp["host"], smtp["port"], timeout=10)
            client.ehlo()
            client.starttls(context=context)
            client.ehlo()
        with client:
            client.login(smtp["username"], config["password"])
    except (OSError, smtplib.SMTPException):
        raise Error("The SMTP server could not be authenticated over a verified encrypted connection. Check the settings and try again.", retryable=True)


def cf_entries(text):
    entries = {}
    for line in text.splitlines():
        if line[:1].isspace() and entries and not line.lstrip().startswith("#"):
            entries[key] += " " + line.strip()
        else:
            match = re.match(r"^([a-zA-Z0-9_]+)\s*=\s*(.*)$", line)
            if match:
                key = match[1]
                entries[key] = match[2]
    return entries


def change_cf(text, changes):
    """Replace exact parameter assignments, preserving unrelated configuration."""
    result = []
    skip = False
    for line in text.splitlines(keepends=True):
        if line[:1].isspace() and not line.lstrip().startswith("#"):
            if not skip:
                result.append(line)
            continue
        match = re.match(r"^([a-zA-Z0-9_]+)\s*=", line)
        skip = bool(match and match[1] in changes)
        if not skip:
            result.append(line)
    suffix = "".join("%s = %s\n" % (key, value) for key, value in changes.items() if value is not None)
    return "".join(result).rstrip("\n") + "\n" + suffix


def sender_maps(domain, sender):
    # Envelope-only canonical mapping: Reply-To is a header_sender in Postfix.
    escaped = re.escape(domain)
    envelope = "/^([^@]+@%s)$/ $1\n/./ %s\n" % (escaped, sender)
    # SMTP header checks touch only From/Sender. Existing Reply-To, recipients,
    # body and attachments are deliberately left to the ordinary mail pipeline.
    header = (r"/^(From|Sender):[[:space:]]*([^<>]*<)?[^@<>[:space:]]+@%s>?[[:space:]]*$/ DUNNO" % escaped
              + "\n" + r"/^(From|Sender):[[:space:]]*(.*<)[^<>]*>[[:space:]]*$/ REPLACE $1: ${2}%s>" % sender
              + "\n" + r"/^(From|Sender):/ REPLACE $1: %s" % sender + "\n")
    return envelope, header


def journey():
    correlation = {}
    try:
        state = json.loads(ONBOARDING_STATE.read_text())
        if (all(re.fullmatch(r"[a-f0-9]{32}", state.get(key, "")) for key in ("installation_id", "flow_id"))
                and state.get("flow_kind") in ("firstboot", "confconsole")):
            correlation = {key: state[key] for key in ("installation_id", "flow_id", "flow_kind")}
    except (OSError, ValueError, TypeError, AttributeError):
        pass
    return correlation


class Mail:
    def __init__(self, *, recover=True):
        self.state = self.load()
        if recover:
            self.recover()

    def load(self):
        path = STATE_DIR / "state.json"
        try:
            value = json.loads(path.read_text())
            if not isinstance(value, dict):
                raise ValueError()
            return value
        except FileNotFoundError:
            return {}
        except (ValueError, OSError):
            raise Error("Saved Hub settings could not be read. Restore the state file before changing the connection.")

    def save(self):
        atomic(STATE_DIR / "state.json", json.dumps(self.state, sort_keys=True) + "\n")

    def recover(self):
        # A root-only journal covers interruption between config and state writes.
        transaction = self.state.get("applying")
        if not transaction:
            return
        atomic(POSTFIX_DIR / "main.cf", transaction["original"], 0o644)
        self.remove_files(transaction["files"])
        run(["postfix", "reload"])
        self.state.pop("applying")
        self.save()

    def guard(self):
        """A fresh automatic enrollment queues SMTP while Hub is unavailable."""
        text = (POSTFIX_DIR / "main.cf").read_text()
        values = cf_entries(text)
        if self.state.get("active") or values.get("relayhost") or self.state.get("guard"):
            return
        old = values.get("defer_transports")
        held = " ".join(filter(None, (old, "smtp")))
        self.state["guard"] = {"before": old, "value": held}
        self.save()
        atomic(POSTFIX_DIR / "main.cf", change_cf(text, {"defer_transports": held}), 0o644)
        try:
            run(["postfix", "reload"])
        except Error:
            atomic(POSTFIX_DIR / "main.cf", text, 0o644)
            self.state.pop("guard", None)
            self.save()
            raise

    def release_guard(self):
        guard = self.state.get("guard")
        if not guard:
            return
        path = POSTFIX_DIR / "main.cf"
        original = path.read_text()
        if cf_entries(original).get("defer_transports") == guard["value"]:
            self.state["applying"] = {"original": original, "files": []}
            self.save()
            try:
                atomic(path, change_cf(original, {"defer_transports": guard["before"]}), 0o644)
                run(["postfix", "reload"])
            except (Error, OSError):
                self.recover()
                raise
            self.state.pop("applying", None)
        self.state.pop("guard")
        self.save()

    def linked(self):
        # Read older combined state until the next successful configuration change.
        config = self.state.get("link", self.state.get("active", {}))
        return config if config.get("mode") == "hub" else {}

    def apply(self, config, verify=True, restore_sender_policy=None):
        if verify:
            smtp_check(config)
        linked = self.linked()
        original = (POSTFIX_DIR / "main.cf").read_text()
        values = cf_entries(original)
        suffix = secrets.token_hex(8)
        sasl = POSTFIX_DIR / ("turnkey-mail-" + suffix + ".sasl")
        created = [sasl, Path(str(sasl) + ".db")]
        target = "[%s]:%s" % (config["smtp"]["host"], config["smtp"]["port"])
        options = {
            "relayhost": target, "smtp_sasl_auth_enable": "yes",
            "smtp_sasl_password_maps": "hash:" + str(sasl),
            "smtp_sasl_security_options": "noanonymous", "smtp_sasl_tls_security_options": "noanonymous",
            "smtp_tls_security_level": "secure", "smtp_tls_CAfile": "/etc/ssl/certs/ca-certificates.crt",
            "smtp_tls_wrappermode": "yes" if config["smtp"]["port"] == 465 else "no",
            "smtp_fallback_relay": "", "smtp_sasl_auth_soft_bounce": "yes",
        }
        if config["mode"] == "hub":
            envelope, header = sender_maps(config["domain"], config["sender"])
            for extension, content in (("sender", envelope), ("headers", header)):
                path = POSTFIX_DIR / ("turnkey-mail-" + suffix + "." + extension)
                atomic(path, content)
                created.append(path)
            options.update(sender_canonical_classes="envelope_sender",
                           sender_canonical_maps="regexp:" + str(created[2]),
                           smtp_header_checks="regexp:" + str(created[3]))
        elif self.state.get("active", {}).get("mode") == "hub":
            # Switching to custom SMTP restores the prior sender policy.
            for key in ("sender_canonical_classes", "sender_canonical_maps", "smtp_header_checks"):
                options[key] = self.state.get("baseline", {}).get(key)
        options.update(restore_sender_policy or {})
        if self.state.get("guard"):
            options["defer_transports"] = self.state["guard"]["before"]
        guarded_queue = config["mode"] == "hub" and self.state.get("guard")
        initial_options = dict(options)
        if guarded_queue:
            initial_options["defer_transports"] = guarded_queue["value"]
        baseline = dict(self.state.get("baseline", {}))
        for key in options:
            if key not in baseline:
                baseline[key] = values.get(key)
        if self.state.get("guard"):
            baseline["defer_transports"] = self.state["guard"]["before"]
        old_state = json.loads(json.dumps(self.state))
        self.state["applying"] = {"original": original, "files": [str(path) for path in created]}
        self.save()
        try:
            atomic(sasl, "%s %s:%s\n" % (target, config["smtp"]["username"], config["password"]))
            run(["postmap", "hash:" + str(sasl)])
            os.chmod(str(sasl) + ".db", 0o600)
            atomic(POSTFIX_DIR / "main.cf", change_cf(original, initial_options), 0o644)
            run(["postfix", "check"])
            run(["postfix", "reload"])
            if guarded_queue:
                # Canonical maps run at queue intake. Reprocess mail accepted
                # before these maps existed, keeping SMTP held until it is
                # queued for cleanup with the new sender policy installed.
                run(["postsuper", "-r", "ALL"])
                atomic(POSTFIX_DIR / "main.cf", change_cf(original, options), 0o644)
                run(["postfix", "reload"])
            self.state.update(active=config, baseline=baseline, owned_options=options,
                              owned_files=[str(path) for path in created])
            if config["mode"] == "hub" and not linked.get("control_secret"):
                self.state["link"] = dict(config)
            elif linked:
                self.state["link"] = linked
            if config["mode"] == "custom":
                self.state["mail_preference"] = "manual"
            self.state.pop("guard", None)
            self.state.pop("applying", None)
            self.save()
        except (Error, OSError):
            atomic(POSTFIX_DIR / "main.cf", original, 0o644)
            for path in created:
                path.unlink(missing_ok=True)
            with contextlib.suppress(Error):
                run(["postfix", "reload"])
            self.state = old_state
            self.save()
            raise Error("The mail service could not apply these settings. Existing settings were restored.", retryable=True)
        self.remove_files(old_state.get("owned_files", []))

    def remove_files(self, files):
        for name in files:
            path = Path(name)
            if path.parent == POSTFIX_DIR and path.name.startswith("turnkey-mail-"):
                path.unlink(missing_ok=True)

    def enroll(self, token=None, flow=None, background=False):
        if token:
            if not ENROLLMENT_TOKEN.fullmatch(token):
                raise Error("The connection code is invalid. Start a new connection.")
            if self.state.get("enrolled_token_hash") == hashlib.sha256(token.encode()).hexdigest() and self.linked():
                return self.status(refresh=False)
            if self.state.get("pending", {}).get("token") != token:
                self.state["pending"] = {"token": token, "control_secret": secrets.token_urlsafe(32),
                                         "dns_password": secrets.token_urlsafe(32),
                                         "flow": journey() if flow is None else flow}
            self.save()
        pending = self.state.get("pending")
        if not pending:
            return self.status(refresh=False)
        if self.state.get('mail_preference', 'hub') == 'hub':
            self.guard()
        try:
            result = request("enroll", {key: pending[key] for key in ("token", "control_secret", "dns_password")})
            if result.get("version") != 2 or not re.fullmatch(r"[a-f0-9]{32}", result.get("device_id", "")):
                raise Error("The Hub returned an invalid connection.")
            remove_daily_backup()
            if self.linked().get("device_id") != result["device_id"]:
                HUB_EMAIL_CACHE.unlink(missing_ok=True)
                for key in ("smtp_secret", "backup_secret", "services"):
                    self.state.pop(key, None)
            self.state["link"] = dict(mode="hub", device_id=result["device_id"],
                                      control_secret=pending["control_secret"], dns_password=pending["dns_password"],
                                      flow=pending.get("flow", {}))
            self.state["enrolled_token_hash"] = hashlib.sha256(pending["token"].encode()).hexdigest()
            for key in ("pending", "pairing", "error"):
                self.state.pop(key, None)
            self.state.setdefault("mail_preference", "hub")
            if background:
                remember_account_email(result.get("account_email"))
                self.queue_provision()
            self.save()
            return self.status(refresh=False) if background else self.sync()
        except Error as error:
            self.state["error"] = {"code": error.code, "message": str(error)}
            if not error.retryable and self.state.get("pending"):
                self.state["pending"]["stopped"] = True
            self.save()
            if self.linked().get("control_secret"):
                return self.status(refresh=False)
            raise

    def retry(self):
        pending = self.state.get("pending")
        if pending and not pending.get("stopped"):
            return self.enroll()
        if self.state.get("error") and self.linked().get("control_secret"):
            return self.sync()
        return self.status(refresh=False)

    def queue_provision(self):
        # Schedule before saving the state so an interrupted command can be retried.
        if RUNTIME:
            RUNTIME.schedule("provision")
        atomic(STATE_DIR / "provision-pending", "")
        self.state["provision_pending"] = True

    def clear_provision(self):
        self.state.pop("provision_pending", None)
        self.save()
        (STATE_DIR / "provision-pending").unlink(missing_ok=True)
        if RUNTIME:
            RUNTIME.schedule("provision", False)

    def fetch_service(self, name):
        link = self.linked()
        public_name = "mail" if name == "email" else name
        version = self.state["services"].get(public_name, {}).get("version", 1)
        result = request("service", {"device_id": link["device_id"], "control_secret": link["control_secret"],
                                     "service": name, "version": version}, "connections")
        return connection_service(name, result, link["device_id"])

    def refresh_provision_service(self, name):
        try:
            return self.fetch_service(name)
        except Error as error:
            if error.code not in ("revoked", "invalid_credentials", "not_authorized"):
                raise
            return {"enabled": False, "status": "revoked"}, None

    def remember_service(self, name, public, secret):
        public_name = "mail" if name == "email" else name
        self.state["services"][public_name] = public
        if name == "dns":
            link = self.linked()
            if secret:
                link["dns_password"] = secret
                link["dyndns"] = {key: public[key] for key in ("hostname", "update_uri")}
            else:
                link.pop("dns_password", None)
                link["dyndns"] = None
        elif name == "backup":
            if secret:
                self.state["backup_secret"] = secret
            else:
                self.state.pop("backup_secret", None)
        elif secret:
            self.state["smtp_secret"] = {"grant_id": public["grant_id"], "password": secret}

    def prepare_daily_backup(self, pairing, device_id, account_id, secret):
        mode = eligible_backup_cron_mode()
        if mode is None:
            raise Error(BACKUP_CRON_CHANGED)
        previous = daily_backup_marker()
        original = previous[1] if previous else ("local" if mode & 0o111 else "managed")
        pending_path = BACKUP_DIR / "hub-managed-daily"
        ready_path = BACKUP_DIR / "hub-daily-initialized"
        ready = backup_file("hub-daily-initialized")
        link = self.linked()
        previous_account_id = link.get("backup_account_id")
        rotate = False
        token = new_token = None
        if previous and secret and type(previous_account_id) is int and previous_account_id == account_id:
            former_device = link.get("device_id")
            token = backup_file("sub_apikey")
            authorization = BACKUP_TOKEN.fullmatch(token or "")
            new_token = "tklbam2.%s.%s" % (device_id, secret)
            former_token = authorization and authorization.group(1) == former_device
            previously_ready = previous[0] == ready == former_device and former_token
            # A completion replay can resume after any of the registry writes.
            resuming = (pairing.get("daily_rotation_device") == device_id and previous[0] == device_id
                        and (ready in (former_device, device_id) or ready is None and former_device == device_id)
                        and (former_token or token == new_token))
            rotate = ((previously_ready or resuming) and backup_file("secret") and backup_file("key")
                      and backup_file("hbr") and backup_file("profile/profile_id")
                      and (BACKUP_DIR / "profile/stamp").is_file())
            if rotate and pairing.get("daily_rotation_device") != device_id:
                pairing["daily_rotation_device"] = device_id
                self.save()

        # The new pending device and old readiness prevent cron from using a
        # stale registry token during rotation. A same-device secret change
        # needs to disarm its readiness explicitly until its new token is saved.
        if ready == device_id and (not rotate or token != new_token):
            ready_path.unlink()
        BACKUP_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
        atomic(pending_path, "%s %s\n" % (device_id, original))
        if rotate:
            if token != new_token:
                atomic(BACKUP_DIR / "sub_apikey", new_token + "\n")
            (BACKUP_DIR / "credentials").unlink(missing_ok=True)
            atomic(ready_path, device_id + "\n")

    def complete(self, pairing, value):
        device_id = value.get("device_id")
        entries = value.get("services")
        if not isinstance(device_id, str) or not DEVICE_ID.fullmatch(device_id) or not isinstance(entries, dict):
            raise Error("The Hub returned an invalid connection.", retryable=True)
        services = {name: connection_service(name, entry, device_id) for name, entry in entries.items()
                    if name in SUPPORTED_SERVICES}
        backup, backup_secret = services.get("backup", ({}, None))
        daily = backup.get("version") == 2
        if daily and not pairing.get("backup_v2_offered"):
            raise Error("The Hub returned backup settings this connection did not request. Start a new connection.")
        account_id = value.get("backup_account_id")
        if type(account_id) is not int or account_id <= 0:
            account_id = None
        if daily:
            self.prepare_daily_backup(pairing, device_id, account_id, backup_secret)
        else:
            remove_daily_backup()
        if not backup_secret:
            forget_backup_auth()
            (BACKUP_DIR / "hub-daily-initialized").unlink(missing_ok=True)
        for field in ("smtp_secret", "backup_secret", "pending", "pairing", "error", "enrolled_token_hash"):
            self.state.pop(field, None)
        self.state["link"] = dict(mode="hub", device_id=device_id, control_secret=pairing["control_secret"],
                                  flow=pairing.get("flow", {}), connections_api=True)
        if daily and account_id is not None:
            self.state["link"]["backup_account_id"] = account_id
        HUB_EMAIL_CACHE.unlink(missing_ok=True)
        email = remember_account_email(value.get("account_email"))
        self.state["services"] = dict(device_id=device_id, connection_status="linked", account_email=email)
        for name, (public, secret) in services.items():
            if public:
                self.remember_service(name, public, secret)
        self.state.setdefault("mail_preference", "hub")
        if (self.state.get("guard") or self.state["services"].get("dns", {}).get("enabled") or
                (self.state["mail_preference"] == "hub" and self.state["services"].get("mail", {}).get("enabled"))):
            self.queue_provision()
            self.save()
        else:
            self.clear_provision()
        return self.status(refresh=False)

    def apply_hub_mail(self, mail):
        if (self.state.get("mail_preference", "hub") == "hub" and mail.get("enabled") and
                mail.get("status") in ("active", "pending_verification") and mail.get("smtp")):
            config = hub_mail_config(self.linked()["device_id"], mail, self.state["smtp_secret"]["password"])
            if self.state.get("active") != config:
                try:
                    self.apply(config)
                except Error as error:
                    # A failed local apply can replace state with the rollback snapshot.
                    self.state["services"]["mail"]["error"] = str(error)

    def provision_connection_mail(self):
        mail = self.state["services"].get("mail", {})
        if self.state.get("mail_preference", "hub") != "hub":
            return self.status(refresh=False)
        if mail.get("enabled"):
            self.guard()
            if mail.get("status") == "unavailable" or mail.get("error"):
                mail, secret = self.refresh_provision_service("email")
                self.remember_service("email", mail, secret)
        if not mail.get("enabled"):
            self.release_guard()
        mail.pop("error", None)
        self.apply_hub_mail(mail)
        self.save()
        return self.status(refresh=False)

    def sync(self):
        link = self.linked()
        if not link.get("control_secret"):
            return self.status(refresh=False)
        proof = {key: link[key] for key in ("device_id", "control_secret")}
        value = request("configure", proof)
        if value.get("device_id") != link["device_id"] or value.get("connection_status") != "linked":
            raise Error("The Hub returned an invalid connection.")
        registration = {}
        mail = value["mail"]
        if mail.get("enabled") and self.state.get("mail_preference", "hub") == "hub":
            self.guard()
            grant = mail.get("grant_id", "")
            if not DEVICE_ID.fullmatch(grant):
                raise Error("The Hub returned an invalid email grant.")
            secret = self.state.get("smtp_secret", {})
            if link.get("connections_api"):
                if secret.get("grant_id") != grant or mail["status"] == "secret_required":
                    mail, new_secret = self.fetch_service("email")
                    self.remember_service("email", mail, new_secret)
                    value["mail"] = mail
            else:
                if secret.get("grant_id") != grant:
                    secret = self.state["smtp_secret"] = {"grant_id": grant, "password": secrets.token_urlsafe(32)}
                    self.save()
                if mail["status"] == "secret_required":
                    registration.update(smtp_grant_id=grant, smtp_password=secret["password"])
        if registration:
            value = request("configure", dict(proof, **registration))
        remember_account_email(value.get("account_email"))
        if link.get("connections_api"):
            for name in ("mail", "dns", "backup"):
                version = self.state["services"].get(name, {}).get("version")
                if version is not None:
                    value[name].setdefault("version", version)
        self.state["services"] = value
        dns = value["dns"]
        link["dyndns"] = {"hostname": dns["hostname"], "update_uri": dns["update_uri"]} if dns["enabled"] else None
        self.save()
        if link.get("connections_api") and not value["mail"].get("enabled"):
            self.release_guard()
        self.apply_hub_mail(value["mail"])
        self.state.pop("error", None)
        self.save()
        return self.status(refresh=False)

    def credential(self, service):
        """Return service-scoped authorization; consumers own initialization."""
        link = self.linked()
        if service == "dns" and link.get("dns_password") and link.get("dyndns"):
            return {"credential": "hubdns2.%s.%s" % (link["device_id"], link["dns_password"]),
                    "hostname": link["dyndns"]["hostname"]}
        if not link.get("control_secret"):
            raise Error("Connect this server by running turnkey-hub, then try again.")
        if link.get("connections_api"):
            if service == "backup" and self.state.get("backup_secret"):
                return {"credential": "tklbam2.%s.%s" % (link["device_id"], self.state["backup_secret"])}
            entry, secret = self.fetch_service(service)
            if service == "dns":
                if not secret:
                    raise Error("Enable DNS for this server in the Hub, then run hubdns-init again.")
                result = {"credential": "hubdns2.%s.%s" % (link["device_id"], secret),
                          "hostname": entry["hostname"]}
            else:
                self.check_backup(entry)
                if not secret:
                    raise Error("Backup setup could not finish. Check backup settings in the Hub and try again.")
                result = {"credential": "tklbam2.%s.%s" % (link["device_id"], secret)}
            self.remember_service(service, entry, secret)
            self.save()
            return result
        proof = {key: link[key] for key in ("device_id", "control_secret")}
        value = request("configure", proof)
        if value.get("device_id") != link["device_id"] or value.get("connection_status") != "linked":
            raise Error("The Hub returned an invalid connection.")
        if service == "dns":
            dns = value["dns"]
            if not dns.get("enabled"):
                raise Error("Enable DNS for this server in the Hub, then run hubdns-init again.")
            secret = link.get("dns_password")
            if not secret:
                raise Error("The DNS credential is missing. Reconnect this server with turnkey-hub.")
            return {"credential": "hubdns2.%s.%s" % (link["device_id"], secret),
                    "hostname": dns["hostname"]}
        backup = value["backup"]
        self.check_backup(backup)
        if not self.state.get("backup_secret"):
            self.state["backup_secret"] = secrets.token_urlsafe(32)
            self.save()
        secret = self.state["backup_secret"]
        result = request("configure", dict(proof, backup_secret=secret))
        if result.get("backup", {}).get("status") != "active":
            raise Error("Backup setup could not finish. Check backup settings in the Hub and try again.")
        return {"credential": "tklbam2.%s.%s" % (link["device_id"], secret)}

    def check_backup(self, backup):
        status = backup.get("status")
        if status == "disabled":
            raise Error("Enable backups for this server in the Hub, then run tklbam-backup again.", code=status)
        if status not in ("active", "secret_required"):
            action = urllib.parse.urljoin(HUB, backup.get("action_url", "/backup/"))
            if urllib.parse.urlsplit(action).netloc != urllib.parse.urlsplit(HUB).netloc:
                action = HUB + "/backup/"
            message = ("Finish migrating your backup account" if status == "migration_required" else
                       "Finish backup setup and connect your AWS account")
            code = status if status in ("setup_required", "migration_required") else "failed"
            raise Error(message + " in the Hub:\n\n  " + action + "\n\nThen retry your command.", code=code)

    def use_hub(self):
        self.state["mail_preference"] = "hub"
        self.save()
        return self.sync()

    def pending_pairing(self):
        """Describe an active pairing without exporting its proof or credentials."""
        pairing = self.state.get("pairing", {})
        expires = pairing.get("expires", 0) - time.time()
        if expires <= 0 or not pairing.get("user_code") or not pairing.get("verification_uri"):
            return {"status": "idle"}
        return {"status": "pending", "user_code": pairing["user_code"],
                "verification_uri": pairing["verification_uri"], "expires_in": math.ceil(expires),
                "interval": pairing["interval"]}

    def start(self, resume=False):
        if resume:
            pending = self.pending_pairing()
            if pending["status"] == "pending":
                return pending
        correlation = journey()
        offers = dict(SUPPORTED_SERVICES)
        if eligible_backup_cron_mode() is None:
            offers["backup"] = [1]
        metadata = dict(correlation, **appliance_description(), supported_services=offers)
        result = request("start", metadata, "connections")
        try:
            uri = urllib.parse.urlsplit(result["verification_uri"])
            if uri.scheme != "https" or uri.netloc != urllib.parse.urlsplit(HUB).netloc:
                raise ValueError()
            if not DEVICE_CODE.fullmatch(result["device_code"]):
                raise ValueError()
            if not re.fullmatch(r"[A-Z0-9]{4}[&-][A-Z0-9]{4}", result["user_code"]):
                raise ValueError()
            ttl = min(900, max(1, int(result["expires_in"])))
            interval = min(30, max(5, int(result["interval"])))
        except (KeyError, TypeError, ValueError):
            raise Error("The Hub returned an invalid connection request.")
        # Older helpers require an ampersand on the wire; display a dash locally.
        result["user_code"] = result["user_code"].replace("&", "-")
        self.state["pairing"] = {"device_code": result["device_code"], "control_secret": secrets.token_urlsafe(32),
                                 "expires": time.time() + ttl,
                                 "interval": interval, "next_poll": 0, "flow": correlation,
                                 "backup_v2_offered": 2 in offers["backup"],
                                 "verification_uri": result["verification_uri"], "user_code": result["user_code"]}
        try:
            from libinithooks.hub_push import validated_notification
            notification = validated_notification(result.get("notification"))
            if notification:
                self.state["pairing"]["notification"] = notification
        except ImportError:
            pass
        self.save()
        if resume:
            return self.pending_pairing()
        return {key: result[key] for key in ("verification_uri", "user_code", "expires_in", "interval")}

    def poll(self, notified=False, background=False, expected_code=None):
        pairing = self.state.get("pairing", {})
        if expected_code is not None and expected_code != pairing.get("user_code"):
            return {"status": "replaced"}
        if pairing.get("expires", 0) <= time.time():
            return {"status": "expired"}
        if pairing.get("backup_v2_offered") and eligible_backup_cron_mode() is None:
            raise Error(BACKUP_CRON_CHANGED)
        if not notified and pairing.get("next_poll", 0) > time.time():
            return {"status": "pending", "interval": pairing["interval"]}
        pairing["next_poll"] = time.time() + pairing["interval"]
        self.save()
        if "control_secret" in pairing:
            try:
                result = request("complete", {key: pairing[key] for key in ("device_code", "control_secret")}, "connections")
            except Error as error:
                if error.retryable:
                    pairing["next_poll"] = 0
                    self.save()
                raise
            if result.get("status") == "linked":
                return self.complete(pairing, result)
        else:
            # Let an already-started legacy pairing finish after a package update.
            result = request("device/poll", {"device_code": pairing["device_code"]})
        if result.get("status") == "approved" and "control_secret" not in pairing:
            token = result.get("enrollment_token", "")
            if not isinstance(token, str) or not ENROLLMENT_TOKEN.fullmatch(token):
                raise Error("The Hub returned an invalid connection approval.")
            return self.enroll(token, pairing.get("flow", {}), background=background)
        if result.get("status") not in ("pending", "expired", "denied"):
            raise Error("The Hub returned an invalid connection status.")
        if expected_code is not None and result["status"] != "pending":
            # A browser that reloads or starts again must not resume a denied
            # or remotely expired pairing. Keep the unchanged CLI behavior.
            self.state.pop("pairing")
            self.save()
        return {"status": result["status"], "interval": pairing["interval"]}

    def connection_status(self):
        """Read the Hub's current settings independently of local setup."""
        link = self.linked()
        if not link.get("control_secret"):
            return {"connection_status": "disconnected"}
        device_id = link["device_id"]
        proof = {"device_id": device_id, "control_secret": link["control_secret"]}
        try:
            value = request("status", proof, "connections", timeout=2)
        except Error as error:
            if error.code in ("invalid_credentials", "revoked"):
                return {"connection_status": "disconnected", "device_id": device_id,
                        "reason": error.code}
            raise
        if (value.get("connection_status") != "linked" or value.get("device_id") != device_id
                or not isinstance(value.get("services"), dict)):
            raise Error("The Hub returned an invalid connection status.")
        return value

    def status(self, refresh=True):
        link = self.linked()
        if refresh and link.get("control_secret"):
            return self.sync()
        active = self.state.get("active", {})
        services = self.state.get("services", {})
        return {"device_id": link.get("device_id", ""),
                "status": active.get("status", "linked" if link.get("control_secret") else "connecting" if self.state.get("pending") else "disconnected"),
                "connection_status": "linked" if link.get("control_secret") else "disconnected",
                "mode": active.get("mode", ""), "mail_preference": self.state.get("mail_preference", "hub"),
                "domain": active.get("domain", ""), "sender": active.get("sender", ""),
                "host": active.get("smtp", {}).get("host", ""), "services": services,
                "setup_pending": bool(self.state.get("provision_pending")),
                "message": self.state.get("error", {}).get("message", self.state.get("legacy_dns", "")) or
                           ("Hub service setup is continuing." if self.state.get("provision_pending") else "")}

    def legacy_dns(self):
        return (Path("/var/lib/hubdns/sub_apikey").exists()
                and os.access("/etc/cron.hourly/hubdns-update", os.X_OK))

    def dns_update(self):
        raise Error("Run hubdns-update to update DNS.")

    def reset_mail(self):
        return self.reset(mail_only=True)

    def reset(self, mail_only=False):
        original = (POSTFIX_DIR / "main.cf").read_text()
        values = cf_entries(original)
        restore = {key: self.state.get("baseline", {}).get(key)
                   for key, value in self.state.get("owned_options", {}).items() if values.get(key) == value}
        guard = self.state.get("guard")
        if guard and values.get("defer_transports") == guard["value"]:
            restore["defer_transports"] = guard["before"]
        try:
            if restore:
                atomic(POSTFIX_DIR / "main.cf", change_cf(original, restore), 0o644)
                run(["postfix", "check"])
                run(["postfix", "reload"])
        except Error:
            atomic(POSTFIX_DIR / "main.cf", original, 0o644)
            with contextlib.suppress(Error):
                run(["postfix", "reload"])
            raise
        self.remove_files(self.state.get("owned_files", []))
        names = () if mail_only else ("turnkey-mail-retry", "turnkey-mail-dns")
        for name in names:
            if RUNTIME:
                RUNTIME.schedule("dns-update" if name.endswith("dns") else "retry", False)
                continue
            timer = SYSTEMD_DIR / (name + ".timer")
            if timer.exists():
                run(["systemctl", "disable", "--now", name + ".timer"])
            for extension in ("timer", "service"):
                (SYSTEMD_DIR / (name + "." + extension)).unlink(missing_ok=True)
        if not RUNTIME:
            run(["systemctl", "daemon-reload"])
        if not mail_only:
            remove_daily_backup()
            if self.linked().get("device_id"):
                forget_backup_auth(self.linked()["device_id"])
        retained = {key: value for key, value in self.state.items() if key not in ("active", "baseline", "owned_options", "owned_files", "guard", "applying")} if mail_only else {}
        if mail_only:
            retained["mail_preference"] = "manual"
        if retained and "enrolled_token_hash" in self.state:
            retained["enrolled_token_hash"] = self.state["enrolled_token_hash"]
        if not mail_only:
            HUB_EMAIL_CACHE.unlink(missing_ok=True)
            (STATE_DIR / "provision-pending").unlink(missing_ok=True)
            if RUNTIME:
                RUNTIME.schedule("provision", False)
        self.state = retained
        self.save()
        return {"status": "disconnected"}

    def test(self, recipient):
        if not ADDRESS.fullmatch(recipient) or len(recipient) > 254:
            raise Error("Enter a valid recipient email address.")
        config = self.state.get("active")
        if not config:
            raise Error("Connect a mail relay before sending a test.")
        sender = config.get("sender", "root@localhost")
        message = email.message.EmailMessage()
        message["From"] = sender
        message["To"] = recipient
        message["Subject"] = "TurnKey app email test"
        message.set_content("This message was submitted through your appliance's system mail service.\n")
        run(["/usr/sbin/sendmail", "-i", "-f", sender, "--", recipient], message.as_bytes())
        return {"status": "queued", "message": "Test message accepted by the local mail queue. Check the recipient inbox for delivery."}


def initialize_linked_dns(result):
    """Keep manual DNS settings and refresh an old scoped token on a relink."""
    services = result.get("services", {})
    dns = services.get("dns", {})
    if not dns.get("enabled"):
        return
    try:
        command = ["/usr/bin/hubdns-init"]
        saved = HUBDNS_DIR / "sub_apikey"
        if saved.exists():
            if "version" not in dns:
                return
            token = re.fullmatch(r"hubdns2\.([a-f0-9]{32})\.[A-Za-z0-9_-]{43}",
                                 saved.read_text(errors="replace").strip())
            if not token or token[1] == services.get("device_id"):
                return
            command.append("--force")
        version = subprocess.run(["dpkg-query", "-W", "-f=${Version}", "hubdns"],
                                 capture_output=True, text=True, timeout=5)
        if version.returncode:
            return
        compatible = subprocess.run(["dpkg", "--compare-versions", version.stdout.strip(), "ge", "1.5.0"],
                                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
        if compatible.returncode:
            return
        initialized = subprocess.run(command, stdin=subprocess.DEVNULL,
                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
        if not initialized.returncode:
            return
    except (OSError, subprocess.TimeoutExpired):
        pass
    result["dns_setup_error"] = "Automatic DNS setup could not finish. Run hubdns-init to try again."


@contextlib.contextmanager
def locked():
    STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
    os.chmod(STATE_DIR, 0o700)
    with (STATE_DIR / "lock").open("a") as lock:
        os.chmod(STATE_DIR / "lock", 0o600)
        fcntl.flock(lock, fcntl.LOCK_EX)
        yield


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    enroll = commands.add_parser("enroll")
    enroll.add_argument("--token-stdin", action="store_true", required=True)
    enroll.add_argument("--require-backup", action="store_true")
    credential = commands.add_parser("credential")
    credential.add_argument("service", choices=("dns", "backup"))
    credential.add_argument("--connect", action="store_true")
    connect = commands.add_parser("connect")
    mode = connect.add_mutually_exclusive_group()
    mode.add_argument("--start", action="store_true")
    mode.add_argument("--poll", action="store_true")
    mode.add_argument("--pending", action="store_true")
    connect.add_argument("--resume", action="store_true")
    connect.add_argument("--expected-code")
    connect.add_argument("--notified", action="store_true")
    connect.add_argument("--background", action="store_true")
    custom = commands.add_parser("configure")
    custom.add_argument("--stdin", action="store_true", required=True)
    status = commands.add_parser("status")
    status.add_argument("--local", action="store_true")
    status.add_argument("--read-only", action="store_true", help="Read local status without applying recovery")
    commands.add_parser("connection-status", help="Read current Hub settings without applying them")
    for name in ("reset", "reset-mail", "retry", "dns-update", "sync", "use-hub", "provision"):
        commands.add_parser(name)
    test = commands.add_parser("test")
    test.add_argument("--recipient", required=True)
    for command in commands.choices.values():
        command.add_argument("--json", action="store_true")
    args = parser.parse_args()
    if args.command == "connect" and (args.notified or args.background) and not args.poll:
        parser.error("--notified and --background require --poll")
    if args.command == "connect" and ((args.resume and not args.start) or
                                      (args.expected_code is not None and not args.poll)):
        parser.error("--resume requires --start and --expected-code requires --poll")
    local_read_only = args.command == "status" and args.read_only
    if local_read_only and not args.local:
        parser.error("status --read-only requires --local")
    read_only = local_read_only or args.command == "connection-status"
    try:
        if os.geteuid() != 0:
            raise Error("Run this command as root.")
        os.umask(0o077)
        if args.command == "dns-update":
            os.execv("/usr/bin/hubdns-update", ["hubdns-update"])
        if args.command == "credential" and args.connect and not Mail().linked().get("control_secret"):
            if not sys.stdin.isatty():
                raise Error("Connect this server by running turnkey-hub, then try again.")
            # Linking owns its own lock and interactive output. Keep the exported
            # credential on stdout for the calling service to consume privately.
            result = subprocess.call([HELPER], stdout=sys.stderr)
            if result:
                raise Error("Connection was not completed. Run turnkey-hub to try again.")
        provision_error = None
        # Local status comes from a single snapshot of the atomically replaced
        # state file. Browser reads need neither the write lock nor recovery.
        with (contextlib.nullcontext() if read_only else locked()):
            mail = Mail(recover=not (read_only or (args.command == "connect" and args.pending)))
            was_linked = bool(mail.linked().get("control_secret"))
            if args.command == "enroll":
                result = mail.enroll(sys.stdin.read(512).strip())
            elif args.command == "credential":
                result = mail.credential(args.service)
            elif args.command == "configure":
                try:
                    raw = sys.stdin.read(MAX_JSON + 1)
                    if len(raw) > MAX_JSON:
                        raise ValueError()
                    config = json.loads(raw)
                    mail.apply(checked_config(config, config["password"], custom=True))
                    for field in ("pending", "pairing", "error"):
                        mail.state.pop(field, None)
                    mail.save()
                    result = mail.status(refresh=False)
                except (ValueError, KeyError, TypeError):
                    raise Error("The custom SMTP settings are invalid.")
            elif args.command == "connect":
                if args.pending:
                    result = mail.pending_pairing()
                elif args.poll:
                    result = mail.poll(notified=args.notified, background=args.background,
                                       expected_code=args.expected_code)
                else:
                    result = mail.start(resume=True) if args.resume else mail.start()
            elif args.command == "provision":
                if mail.state.get("provision_pending"):
                    if mail.linked().get("connections_api"):
                        try:
                            result = mail.provision_connection_mail()
                        except (Error, OSError):
                            # DNS uses its own credential and can proceed if email is unavailable.
                            provision_error = "Hub email setup could not finish; it will be retried."
                            result = mail.status(refresh=False)
                    else:
                        result = mail.sync()
                    service_mail = result.get("services", {}).get("mail", {})
                    if (service_mail.get("error") or
                            (result.get("mail_preference") == "hub" and service_mail.get("enabled") and
                             (not service_mail.get("smtp") or result.get("mode") != "hub"))):
                        provision_error = "Hub email setup could not finish; it will be retried."
                        if not mail.linked().get("connections_api"):
                            raise Error(provision_error, retryable=True)
                elif mail.state.get("pending"):
                    result = mail.enroll()
                else:
                    (STATE_DIR / "provision-pending").unlink(missing_ok=True)
                    result = mail.status(refresh=False)
            elif args.command == "dns-update":
                result = mail.dns_update()
            elif args.command == "test":
                result = mail.test(args.recipient)
            elif args.command == "status":
                result = mail.status(refresh=not args.local)
            else:
                result = getattr(mail, args.command.replace("-", "_"))()
        if args.command == "connect" and not (args.start or args.poll or args.pending):
            print("Open %s\nConnection code: %s\nSign in or create a free Hub account, then approve this appliance.\nWaiting for approval (Ctrl-C to cancel)..." %
                  (result["verification_uri"], result["user_code"]), flush=True)
            while True:
                time.sleep(result.get("interval", 5))
                with locked():
                    result = Mail().poll()
                if result.get("status") != "pending" or result.get("domain"):
                    break
            if result.get("status") in ("expired", "denied"):
                raise Error(ERRORS[result["status"]], code=result["status"])
        if result.get("setup_pending") and args.command == "connect":
            from libinithooks import hub_runtime
            hub_runtime.start_provision()
        if ((args.command in ("enroll", "connect", "retry") and not was_linked and
                not result.get("setup_pending")) or args.command == "provision") and \
                result.get("connection_status") == "linked":
            initialize_linked_dns(result)
        if args.command == "provision":
            if result.get("dns_setup_error"):
                if not mail.linked().get("connections_api"):
                    raise Error(result["dns_setup_error"], retryable=True)
                with locked():
                    current = Mail()
                    if current.linked().get("device_id") == mail.linked().get("device_id"):
                        dns, secret = current.refresh_provision_service("dns")
                        current.remember_service("dns", dns, secret)
                        current.save()
                        if dns.get("enabled"):
                            raise Error(result["dns_setup_error"], retryable=True)
                        result = current.status(refresh=False)
                result.pop("dns_setup_error", None)
            if provision_error:
                raise Error(provision_error, retryable=True)
            with locked():
                current = Mail()
                if current.linked().get("device_id") == mail.linked().get("device_id"):
                    current.clear_provision()
        if args.command == "enroll" and args.require_backup:
            run(["tklbam-init"], timeout=60)
        if result.get("dns_setup_error") and not args.json:
            print(result["dns_setup_error"], file=sys.stderr)
        if args.json or args.command == "credential":
            print(json.dumps(result, sort_keys=True))
        elif args.command == "connection-status":
            print("Hub connection: %s" % result["connection_status"])
        elif result.get("message"):
            print(result["message"])
        else:
            print("%s connection: %s%s" % ("Mail" if args.command == "configure" else "Hub", result.get("status", "waiting"),
                  (" (" + result["domain"] + ")") if result.get("domain") else ""))
        return 0
    except Error as error:
        if args.json:
            print(json.dumps({"status": "error", "error": error.code, "message": str(error),
                              "retryable": error.retryable}))
        else:
            print(str(error), file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        print("Linking cancelled. Existing service settings were kept.", file=sys.stderr)
        return 130
    except (OSError, ValueError, KeyError, TypeError):
        # Never emit tracebacks that could contain tokens or configuration.
        label = "Mail setup" if args.command in ("configure", "test", "reset-mail") else "Hub services setup"
        print(label + " could not finish. Check the system services and try again.", file=sys.stderr)
        return 1


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