#!/usr/bin/env python3
"""Synchronize Roundcube/webmail Nginx server_names and mail SAN certificate."""

from __future__ import annotations

import argparse
import fcntl
import http.client
import ipaddress
import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import time
from pathlib import Path

MAIL_DOMAINS_FILE = Path("/etc/d54-hostpanel/mail/live/domains")
NGINX_SITES_ENABLED = Path("/etc/nginx/sites-enabled")
WEBMAIL_NGINX_PATHS = (
    Path("/etc/nginx/conf.d/d54-hostpanel-webmail.conf"),
    Path("/etc/nginx/conf.d/d54-hostpanel-mail-acme.conf"),
)
CERT_NAME = "d54-hostpanel-mail"
CERT_FULLCHAIN = Path(f"/etc/letsencrypt/live/{CERT_NAME}/fullchain.pem")
ACME_WEBROOT = Path("/var/www/d54-hostpanel-acme")
LOCK_FILE = Path("/run/d54-sync-mail-ssl.lock")
STATE_FILE = Path("/var/lib/d54-hostpanel/mail-ssl-sync-state.json")
MAX_SANS = 95
BACKOFF_SECONDS = 3600

DOMAIN_RE = re.compile(
    r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$"
)
SERVER_NAME_RE = re.compile(r"^([ \t]*server_name\s+)([^;]+)(;[ \t]*)$", re.MULTILINE)


def run_cmd(cmd: list[str], timeout: int = 15) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        timeout=timeout,
        check=False,
    )


def valid_domain(name: str) -> bool:
    return bool(name and len(name) <= 253 and DOMAIN_RE.match(name))


def detect_base_host() -> str:
    res = run_cmd(["postconf", "-h", "myhostname"], timeout=5)
    candidate = res.stdout.strip().rstrip(".").lower() if res.returncode == 0 else ""
    if valid_domain(candidate):
        return candidate
    return "mail.d54.com.tr"


def detect_server_ips() -> tuple[str, str | None]:
    ipv4: str | None = None
    res4 = run_cmd(["ip", "-4", "route", "get", "1.1.1.1"], timeout=5)
    if res4.returncode == 0:
        m = re.search(r"\bsrc\s+([0-9.]+)\b", res4.stdout)
        if m:
            try:
                addr = ipaddress.IPv4Address(m.group(1))
                if not (addr.is_private or addr.is_loopback or addr.is_link_local):
                    ipv4 = str(addr)
            except ipaddress.AddressValueError:
                pass
    if not ipv4:
        res_hi = run_cmd(["hostname", "-I"], timeout=5)
        if res_hi.returncode == 0:
            for tok in res_hi.stdout.split():
                try:
                    addr = ipaddress.IPv4Address(tok)
                    if not (addr.is_private or addr.is_loopback or addr.is_link_local):
                        ipv4 = str(addr)
                        break
                except ipaddress.AddressValueError:
                    continue
    if not ipv4:
        raise RuntimeError("Could not detect public IPv4 address for server")

    ipv6: str | None = None
    res6 = run_cmd(["ip", "-6", "route", "get", "2606:4700:4700::1111"], timeout=5)
    if res6.returncode == 0:
        m6 = re.search(r"\bsrc\s+([0-9a-fA-F:]+)\b", res6.stdout)
        if m6:
            try:
                addr6 = ipaddress.IPv6Address(m6.group(1))
                if addr6.is_global:
                    ipv6 = str(addr6)
            except ipaddress.AddressValueError:
                pass
    return ipv4, ipv6


def read_current_sans() -> list[str]:
    if not CERT_FULLCHAIN.exists():
        return []
    res = run_cmd(
        ["openssl", "x509", "-in", str(CERT_FULLCHAIN), "-noout", "-ext", "subjectAltName"],
        timeout=10,
    )
    if res.returncode != 0:
        return []
    sans: list[str] = []
    for m in re.finditer(r"DNS:([^\s,]+)", res.stdout):
        host = m.group(1).strip().rstrip(".").lower()
        if valid_domain(host) and host not in sans:
            sans.append(host)
    return sans


def collect_candidates(base_host: str, current_sans: list[str]) -> list[str]:
    discovered: set[str] = set()
    if MAIL_DOMAINS_FILE.exists():
        for line in MAIL_DOMAINS_FILE.read_text(encoding="utf-8", errors="ignore").splitlines():
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            dom = line.split()[0].strip().rstrip(".").lower()
            if valid_domain(dom):
                discovered.add(f"mail.{dom}")

    if NGINX_SITES_ENABLED.is_dir():
        for conf in sorted(NGINX_SITES_ENABLED.glob("*.conf")):
            dom = conf.stem.strip().rstrip(".").lower()
            if (
                not dom
                or dom == "default"
                or dom.startswith("d54-hostpanel-")
                or dom.startswith("mail.")
                or dom.startswith("panel.")
            ):
                continue
            if valid_domain(dom):
                discovered.add(f"mail.{dom}")

    ordered: list[str] = []
    seen: set[str] = set()

    def add(host: str) -> None:
        if host not in seen:
            seen.add(host)
            ordered.append(host)

    add(base_host)
    for host in sorted(current_sans):
        add(host)
    for host in sorted(discovered):
        add(host)
    return ordered


def dig_records(server: str | None, name: str, rtype: str) -> list[str]:
    cmd = ["dig", "+short", "+time=3", "+tries=1"]
    if server:
        cmd.append(f"@{server}")
    cmd.extend([name, rtype])
    res = run_cmd(cmd, timeout=6)
    if res.returncode != 0:
        return []
    out: list[str] = []
    for raw in res.stdout.splitlines():
        line = raw.strip()
        if not line or line.startswith(";"):
            continue
        out.append(line)
    return out


def parse_ips(lines: list[str], family: int) -> list[str]:
    ips: list[str] = []
    cls = ipaddress.IPv4Address if family == 4 else ipaddress.IPv6Address
    for line in lines:
        try:
            ips.append(str(cls(line.strip())))
        except ipaddress.AddressValueError:
            continue
    return ips


def dig_authority_ns(server: str, name: str) -> tuple[list[str], list[str]]:
    res = run_cmd(
        ["dig", "+norecurse", "+noall", "+authority", "+answer", "+time=3", "+tries=1", f"@{server}", name, "NS"],
        timeout=6,
    )
    if res.returncode != 0:
        return [], []
    exact: list[str] = []
    referral: list[str] = []
    for raw in res.stdout.splitlines():
        parts = raw.split()
        if len(parts) >= 5 and parts[3].upper() == "NS":
            owner = parts[0].rstrip(".").lower()
            ns = parts[4].rstrip(".").lower()
            if not valid_domain(ns):
                continue
            if owner == name and ns not in exact:
                exact.append(ns)
            elif name.endswith(f".{owner}") and ns not in referral:
                referral.append(ns)
    return exact, referral


def resolve_authoritative_ns(apex: str) -> list[str]:
    # Query the TLD nameserver directly to avoid stale recursive NS caches (like 1.1.1.1 right after NS cutover).
    tld = apex.rsplit(".", 1)[-1]
    tld_ns_list: list[str] = []
    for resolver in ("1.1.1.1", "8.8.8.8"):
        lines = dig_records(resolver, tld, "NS")
        tld_ns_list = [line.rstrip(".").lower() for line in lines if valid_domain(line.rstrip(".").lower())]
        if tld_ns_list:
            break

    for tld_ns in tld_ns_list[:2]:
        exact, referral = dig_authority_ns(tld_ns, apex)
        if exact:
            return exact[:2]
        for ref_ns in referral[:2]:
            exact2, _ = dig_authority_ns(ref_ns, apex)
            if exact2:
                return exact2[:2]

    # Fallback: prefer 8.8.8.8 then 1.1.1.1 if direct TLD referral fails.
    for resolver in ("8.8.8.8", "1.1.1.1"):
        lines = dig_records(resolver, apex, "NS")
        ns_hosts = [line.rstrip(".").lower() for line in lines if valid_domain(line.rstrip(".").lower())]
        if ns_hosts:
            return ns_hosts[:2]
    return []


def validate_dns(host: str, server_ipv4: str, server_ipv6: str | None) -> tuple[bool, str]:
    apex = host[5:] if host.startswith("mail.") else host
    ns_hosts = resolve_authoritative_ns(apex)

    a_records: list[str] = []
    aaaa_records: list[str] = []
    for ns in ns_hosts:
        a_lines = dig_records(ns, host, "A")
        a_ips = parse_ips(a_lines, 4)
        if a_ips:
            a_records = a_ips
            aaaa_records = parse_ips(dig_records(ns, host, "AAAA"), 6)
            break

    if not a_records:
        for resolver in ("1.1.1.1", "8.8.8.8"):
            a_ips = parse_ips(dig_records(resolver, host, "A"), 4)
            if a_ips:
                a_records = a_ips
                aaaa_records = parse_ips(dig_records(resolver, host, "AAAA"), 6)
                break

    if not a_records:
        return False, "no_a_record"
    if set(a_records) != {server_ipv4}:
        return False, f"dns_mismatch({','.join(sorted(set(a_records)))})"
    if aaaa_records:
        if server_ipv6 is None or set(aaaa_records) != {server_ipv6}:
            return False, f"aaaa_mismatch({','.join(sorted(set(aaaa_records)))})"
    return True, "ok"


def find_webmail_nginx_conf() -> Path | None:
    for path in WEBMAIL_NGINX_PATHS:
        if path.exists():
            return path
    return None


def sync_nginx_server_names(conf_path: Path, hosts: list[str], dry_run: bool) -> bool:
    original = conf_path.read_text(encoding="utf-8")
    new_names = " ".join(hosts)
    updated, count = SERVER_NAME_RE.subn(
        lambda m: f"{m.group(1)}{new_names}{m.group(3)}",
        original,
    )
    if count == 0:
        raise RuntimeError(f"No server_name directive found in {conf_path}")
    if updated == original:
        return False
    if dry_run:
        return True

    conf_path.write_text(updated, encoding="utf-8")
    test_res = run_cmd(["nginx", "-t"], timeout=15)
    if test_res.returncode != 0:
        conf_path.write_text(original, encoding="utf-8")
        raise RuntimeError(f"nginx -t failed after updating {conf_path}: {test_res.stderr.strip()}")
    reload_res = run_cmd(["systemctl", "reload", "nginx.service"], timeout=15)
    if reload_res.returncode != 0:
        raise RuntimeError(f"systemctl reload nginx.service failed: {reload_res.stderr.strip()}")
    return True


def probe_http_01(hosts: list[str]) -> tuple[list[str], dict[str, str]]:
    challenge_dir = ACME_WEBROOT / ".well-known" / "acme-challenge"
    challenge_dir.mkdir(parents=True, exist_ok=True)
    os.chmod(ACME_WEBROOT, 0o755)
    os.chmod(ACME_WEBROOT / ".well-known", 0o755)
    os.chmod(challenge_dir, 0o755)

    token = secrets.token_hex(16)
    probe_name = f"d54-probe-{token}"
    probe_file = challenge_dir / probe_name
    probe_file.write_text(token, encoding="utf-8")
    os.chmod(probe_file, 0o644)

    verified: list[str] = []
    failed: dict[str, str] = {}
    try:
        for host in hosts:
            conn: http.client.HTTPConnection | None = None
            try:
                conn = http.client.HTTPConnection("127.0.0.1", 80, timeout=5)
                conn.request(
                    "GET",
                    f"/.well-known/acme-challenge/{probe_name}",
                    headers={"Host": host, "Connection": "close"},
                )
                resp = conn.getresponse()
                body = resp.read().decode("utf-8", errors="replace").strip()
                if resp.status == 200 and body == token:
                    verified.append(host)
                else:
                    failed[host] = f"http_{resp.status}"
            except OSError as exc:
                failed[host] = f"probe_err({exc})"
            finally:
                if conn is not None:
                    conn.close()
    finally:
        try:
            probe_file.unlink()
        except FileNotFoundError:
            pass
    return verified, failed


def load_state() -> dict:
    if not STATE_FILE.exists():
        return {}
    try:
        return json.loads(STATE_FILE.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {}


def save_state(state: dict | None) -> None:
    if state is None:
        try:
            STATE_FILE.unlink()
        except FileNotFoundError:
            pass
        return
    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    os.chmod(STATE_FILE.parent, 0o755)
    tmp = STATE_FILE.with_suffix(".tmp")
    tmp.write_text(json.dumps(state, indent=2, sort_keys=True), encoding="utf-8")
    os.chmod(tmp, 0o644)
    tmp.replace(STATE_FILE)


def cap_hosts(base_host: str, current_sans: list[str], valid_hosts: list[str]) -> list[str]:
    valid_set = set(valid_hosts)
    ordered: list[str] = []
    seen: set[str] = set()

    def add(host: str) -> None:
        if host in valid_set and host not in seen and len(ordered) < MAX_SANS:
            seen.add(host)
            ordered.append(host)

    add(base_host)
    for host in sorted(current_sans):
        add(host)
    for host in sorted(valid_hosts):
        add(host)
    return ordered


def main() -> int:
    parser = argparse.ArgumentParser(description="Sync mail.<domain> Nginx server_name and SSL SANs")
    parser.add_argument("--dry-run", action="store_true", help="Inspect without modifying Nginx or certs")
    parser.add_argument("--force", action="store_true", help="Bypass recent failure backoff")
    args = parser.parse_args()

    LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
    lock_fh = LOCK_FILE.open("w", encoding="utf-8")
    try:
        fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        print("OK: d54-sync-mail-ssl already running")
        return 0

    for binary in ("openssl", "dig", "certbot", "nginx"):
        if not shutil.which(binary):
            print(f"ERROR: required binary missing: {binary}", file=sys.stderr)
            return 1

    base_host = detect_base_host()
    server_ipv4, server_ipv6 = detect_server_ips()
    current_sans = read_current_sans()
    candidates = collect_candidates(base_host, current_sans)

    dns_valid: list[str] = []
    skipped: dict[str, str] = {}
    for host in candidates:
        ok, reason = validate_dns(host, server_ipv4, server_ipv6)
        if ok:
            dns_valid.append(host)
        else:
            skipped[host] = reason

    if base_host not in dns_valid:
        print(
            f"ERROR: base host {base_host} failed DNS validation ({skipped.get(base_host, 'unknown')})",
            file=sys.stderr,
        )
        return 1

    nginx_conf = find_webmail_nginx_conf()
    nginx_changed = False
    if nginx_conf is not None:
        nginx_hosts: list[str] = []
        for h in [base_host] + sorted(current_sans) + sorted(dns_valid):
            if h not in nginx_hosts and len(nginx_hosts) < MAX_SANS:
                nginx_hosts.append(h)
        nginx_changed = sync_nginx_server_names(nginx_conf, nginx_hosts, args.dry_run)

    probed_ok, probe_failed = probe_http_01(dns_valid)
    for host, reason in probe_failed.items():
        if args.dry_run and nginx_changed and host not in current_sans:
            skipped[host] = f"pending_nginx_update({reason})"
        else:
            skipped[host] = reason

    desired_verified = cap_hosts(base_host, current_sans, probed_ok if not args.dry_run else dns_valid)
    if args.dry_run:
        # In dry-run, keep probe-passing hosts plus newly added DNS-valid hosts whose Nginx change wasn't applied yet.
        verified_set = set(probed_ok) | (set(dns_valid) - set(current_sans))
        desired_verified = cap_hosts(base_host, current_sans, sorted(verified_set))
    else:
        desired_verified = cap_hosts(base_host, current_sans, probed_ok)

    if base_host not in desired_verified:
        print(f"ERROR: base host {base_host} failed HTTP-01 probe", file=sys.stderr)
        return 1

    missing = [h for h in desired_verified if h not in current_sans]
    removed = [h for h in current_sans if h not in desired_verified]

    if not missing:
        print(
            f"OK: {CERT_NAME} up-to-date ({len(current_sans)} SANs), skipped: {len(skipped)}"
            + (f" [{', '.join(f'{k}={v}' for k, v in sorted(skipped.items()))}]" if skipped else "")
        )
        return 0

    if args.dry_run:
        print(
            f"DRY-RUN: {CERT_NAME} current={len(current_sans)}, would_add={','.join(missing)}"
            + (f", would_drop={','.join(removed)}" if removed else "")
            + (f", nginx_changed={nginx_changed}" if nginx_conf else "")
            + (f", skipped=[{', '.join(f'{k}={v}' for k, v in sorted(skipped.items()))}]" if skipped else "")
        )
        return 0

    missing_key = sorted(missing)
    if not args.force:
        state = load_state()
        last_ts = float(state.get("failed_at", 0))
        if state.get("missing") == missing_key and (time.time() - last_ts) < BACKOFF_SECONDS:
            print(
                f"SKIP: backoff active for [{', '.join(missing_key)}] "
                f"(last failure {int(time.time() - last_ts)}s ago)"
            )
            return 0

    cmd = [
        "certbot",
        "certonly",
        "--non-interactive",
        "--agree-tos",
        "--cert-name",
        CERT_NAME,
        "--webroot",
        "--webroot-path",
        str(ACME_WEBROOT),
    ]
    if set(current_sans).issubset(set(desired_verified)):
        cmd.append("--expand")
    for host in desired_verified:
        cmd.extend(["-d", host])

    cb_res = run_cmd(cmd, timeout=180)
    if cb_res.returncode != 0:
        err_tail = "\n".join((cb_res.stderr or cb_res.stdout).splitlines()[-20:])
        save_state(
            {
                "failed_at": time.time(),
                "missing": missing_key,
                "error": err_tail,
            }
        )
        print(f"ERROR: certbot failed for [{', '.join(missing_key)}]:\n{err_tail}", file=sys.stderr)
        return 1

    save_state(None)
    run_cmd(["systemctl", "reload", "nginx.service", "postfix.service", "dovecot.service"], timeout=20)
    print(
        f"OK: {CERT_NAME} updated ({len(desired_verified)} SANs), added: {', '.join(missing)}"
        + (f", skipped: {len(skipped)}" if skipped else "")
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
