#!/usr/bin/env python3
'''
ALFRED SOVEREIGN CLOUD CONTROL PANEL & DATACENTER — MASTER OTA v2 BUILDER & ZERO-PII GATE
ALFRED_OTA_CHAIN_V2=1

Packages the generic Control Panel UI, encrypted `.alfenc` bytecode vault + `alfred-license-guard`,
GPU Gateway CLIs, Sysadmin Daemon, and v2 Cumulative Catch-Up OTA Engine into a Zero-PII
verified Datacenter + Control Panel OTA release.
Preserves and appends to ordered `releases[]` chains in BOTH:
  - /var/www/alfredlinux.com/web/ota/datacenter/manifest.json
  - /var/www/alfredlinux.com/web/ota/panel/manifest.json
and cryptographically signs both manifests + per-release entries with Ed25519 when the
signing key is present.
'''
import argparse
import glob
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import time

sys.path.insert(0, "/usr/local/lib/alfred-ota")
import chain_engine as ce

STAGE_DIR = "/tmp/alfred-panel-ota-stage"
OTA_ROOT_DIR = "/var/www/alfredlinux.com/web/ota"
OTA_BASE_DIR = os.path.join(OTA_ROOT_DIR, "datacenter")
BUNDLES_DIR = os.path.join(OTA_BASE_DIR, "bundles")
MANIFEST_PATH = os.path.join(OTA_BASE_DIR, "manifest.json")
PANEL_OTA_DIR = os.path.join(OTA_ROOT_DIR, "panel")
PANEL_MANIFEST_PATH = os.path.join(PANEL_OTA_DIR, "manifest.json")
SECRET_KEY_PATH = "/home/gositeme/law/alfred-ota-signing-keys/ota-ed25519.secret"
PUB_KEY_PATH = "/home/gositeme/law/alfred-ota-signing-keys/ota-ed25519.pub"

FORBIDDEN_PATTERNS = [
    (r"15\.235\.50\.60", "Private source server IP (15.235.50.60)"),
    (r"192\.168\.1\.246", "Private LAN IP (192.168.1.246)"),
    (r"142\.99\.0\.58", "Private WAN IP (142.99.0.58)"),
    (r"\bgositeme\b", "Private username/database identifier (gositeme)"),
    (r"lavocat\.ca", "Personal domain (lavocat.ca)"),
    (r"soundstudiopro\.com", "Personal domain (soundstudiopro.com)"),
    (r"faitmoiunsite\.com", "Master admin domain (faitmoiunsite.com)"),
    (r"BEGIN OPENSSH PRIVATE KEY", "Embedded SSH private key"),
    (r"drumahon\.com", "Tenant domain (drumahon.com)"),
    (r"\bcoopfath\b", "Tenant username (coopfath)"),
    (r"\bcarlos\b", "Tenant username (carlos)"),
]

EXCLUDE_SUBPATHS = {
    "lib/config.inc.php",
    "tenant_sso.php",
    "temp",
    "ota",
}


def run_pii_scan(root_dir: str) -> list:
    violations = []
    compiled = [(re.compile(pat, re.IGNORECASE), desc) for pat, desc in FORBIDDEN_PATTERNS]
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for fname in filenames:
            fpath = os.path.join(dirpath, fname)
            if os.path.islink(fpath):
                continue
            if fname.endswith((".png", ".jpg", ".jpeg", ".gif", ".ico", ".woff", ".woff2", ".ttf", ".eot", ".pyc", ".so", ".alfenc")):
                continue
            if os.path.basename(fpath) in ("alfred-license", "alfred-license.bin", "alfred-license-guard", "alfred-build-panel-ota"):
                continue
            try:
                content = open(fpath, "r", encoding="utf-8", errors="ignore").read()
            except Exception:
                continue
            rel = os.path.relpath(fpath, root_dir)
            content = re.sub(r'https://gositeme\.com/(?:api\b[^\s"\x27<>]*|alfred-credits-checkout\.php[^\s"\x27<>]*|pricing\.php[^\s"\x27<>]*)', '', content, flags=re.I)
            is_ide_ext = rel.startswith("opt/alfred-ide/extensions-bundled/") or rel == "usr/local/bin/alfred-rebrand-ide.py"
            for regex, desc in compiled:
                if is_ide_ext and r"\bgositeme\b" in regex.pattern:
                    continue
                m = regex.search(content)
                if m:
                    violations.append({
                        "file": rel,
                        "match": m.group(0),
                        "reason": desc,
                    })
    return violations


def copy_panel_tree(src_web: str, dst_web: str):
    for dirpath, dirnames, filenames in os.walk(src_web):
        rel_dir = os.path.relpath(dirpath, src_web)
        if rel_dir == ".":
            rel_dir = ""
        if any(rel_dir == ex or rel_dir.startswith(ex + "/") for ex in EXCLUDE_SUBPATHS):
            dirnames[:] = []
            continue
        dirnames[:] = [d for d in dirnames if not d.startswith(".bak") and d != "__pycache__"]
        target_dir = os.path.join(dst_web, rel_dir) if rel_dir else dst_web
        os.makedirs(target_dir, exist_ok=True)
        for fname in filenames:
            if ".bak" in fname or fname.endswith((".swp", ".tmp", ".orig")):
                continue
            rel_file = os.path.join(rel_dir, fname) if rel_dir else fname
            if rel_file in EXCLUDE_SUBPATHS:
                continue
            sfile = os.path.join(dirpath, fname)
            dfile = os.path.join(target_dir, fname)
            if os.path.islink(sfile):
                continue
            shutil.copy2(sfile, dfile)


def main():
    parser = argparse.ArgumentParser(description="Build Zero-PII Alfred Cloud Control Panel & Datacenter OTA v2 Bundle")
    parser.add_argument("--version", default="", help="Datacenter release version (e.g. 1.3.11)")
    parser.add_argument("--panel-version", default="", help="Control Panel version (e.g. 31.0.15)")
    parser.add_argument("--notes", default="", help="Release notes")
    parser.add_argument("--kind", choices=["delta", "cumulative"], default="delta", help="Release kind in v2 chain")
    parser.add_argument("--min-from-version", default="1.0.0", help="Minimum version required before applying")
    parser.add_argument("--covers-from", default="", help="For cumulative milestones, earliest skipped version covered")
    parser.add_argument("--reboot-required", action="store_true", help="Mark release as requiring reboot")
    parser.add_argument("--scan-only", action="store_true", help="Run Zero-PII scan only without packaging")
    parser.add_argument("--json", action="store_true", help="Output JSON result")
    args = parser.parse_args()

    if os.path.exists(STAGE_DIR):
        shutil.rmtree(STAGE_DIR)
    os.makedirs(STAGE_DIR, exist_ok=True)

    # 1. Stage Control Panel web tree (excluding .bak* and recursive ota/ cache)
    dst_web = os.path.join(STAGE_DIR, "usr/local/ispconfig/interface/web")
    copy_panel_tree("/usr/local/ispconfig/interface/web", dst_web)

    # 2. Stage backend agent, v2 OTA updater & chain engine, license guard/verifier, GPU CLIs & encrypted .alfenc vaults
    os.makedirs(os.path.join(STAGE_DIR, "usr/local/bin"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "usr/local/sbin"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "usr/local/lib/alfred-ota"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "usr/local/libexec"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "etc/alfred/license"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "etc/alfred/keys"), exist_ok=True)

    bfile_list = [
        "/usr/local/bin/alfred-sysadmin-agent.py",
        "/usr/local/bin/alfred-datacenter-update",
        "/usr/local/bin/alfred-ota-updater",
        "/usr/local/bin/alfred-license",
        "/usr/local/bin/alfred-license.bin",
        "/usr/local/bin/alfred-license-guard",
        "/usr/local/bin/alfred-build-panel-ota",
        "/usr/local/bin/alfred-ha-clone-sync",
        "/usr/local/bin/citadel_installer.py",
        "/usr/local/bin/citadel_uninstaller.py",
        "/usr/local/bin/citadel_domain_vhost.py",
        "/usr/local/bin/alfred-tenant-ai-gateway",
        "/usr/local/bin/alfred-enforce-port-gate.py",
        "/usr/local/bin/alfred-configure-dovecot-postfix.py",
        "/usr/local/bin/alfred-fix-roundcube-smtp.py",
        "/usr/local/bin/alfred-upgrade",
        "/usr/local/libexec/alfred-update-apply",
        "/usr/local/lib/alfred-ota/chain_engine.py",
    ]
    # Also include GPU studio CLIs
    for gp in glob.glob("/usr/local/bin/alfred-gpu-*"):
        if os.path.isfile(gp) and gp not in bfile_list:
            bfile_list.append(gp)

    for bfile in bfile_list:
        if os.path.isfile(bfile):
            dst = os.path.join(STAGE_DIR, bfile.lstrip("/"))
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            shutil.copy2(bfile, dst)
            os.chmod(dst, 0o755)

    if os.path.exists("/usr/local/sbin/alfred-iso-factory-reset"):
        shutil.copy2("/usr/local/sbin/alfred-iso-factory-reset", os.path.join(STAGE_DIR, "usr/local/sbin/alfred-iso-factory-reset"))
        os.chmod(os.path.join(STAGE_DIR, "usr/local/sbin/alfred-iso-factory-reset"), 0o755)

    for pubf in ("/etc/alfred/license/authority.pub", "/etc/alfred/keys/ota-ed25519.pub"):
        if os.path.isfile(pubf):
            dst = os.path.join(STAGE_DIR, pubf.lstrip("/"))
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            shutil.copy2(pubf, dst)

    # Stage encrypted AES-256-GCM .alfenc Control Panel vaults + security_settings.ini!
    os.makedirs(os.path.join(STAGE_DIR, "usr/local/ispconfig/security"), exist_ok=True)
    for secf in glob.glob("/usr/local/ispconfig/security/*.alfenc") + ["/usr/local/ispconfig/security/security_settings.ini"]:
        if os.path.isfile(secf):
            dst = os.path.join(STAGE_DIR, secf.lstrip("/"))
            shutil.copy2(secf, dst)
            os.chmod(dst, 0o640)

    # Stage APT sources & GPG keys
    os.makedirs(os.path.join(STAGE_DIR, "etc/apt/sources.list.d"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "etc/apt/keyrings"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "etc/apt/trusted.gpg.d"), exist_ok=True)
    open(os.path.join(STAGE_DIR, "etc/apt/sources.list"), "w", encoding="utf-8").write("")
    for apt_s in ("non-free.list", "php.list", "rspamd.list", "zz-sources.list"):
        src_a = os.path.join("/etc/apt/sources.list.d", apt_s)
        if os.path.exists(src_a):
            shutil.copy2(src_a, os.path.join(STAGE_DIR, "etc/apt/sources.list.d", apt_s))
    if os.path.exists("/etc/apt/keyrings/rspamd.gpg"):
        shutil.copy2("/etc/apt/keyrings/rspamd.gpg", os.path.join(STAGE_DIR, "etc/apt/keyrings/rspamd.gpg"))
    if os.path.isdir("/etc/apt/trusted.gpg.d"):
        for gpg_f in os.listdir("/etc/apt/trusted.gpg.d"):
            if gpg_f.endswith((".asc", ".gpg")):
                shutil.copy2(os.path.join("/etc/apt/trusted.gpg.d", gpg_f), os.path.join(STAGE_DIR, "etc/apt/trusted.gpg.d", gpg_f))

    # Stage NOC, Cloud Apps, desktop shortcuts & units
    os.makedirs(os.path.join(STAGE_DIR, "usr/share/alfred-ota"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "var/www/apps/searxng"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "var/www/apps/bigbluebutton"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "usr/share/applications"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "etc/skel/Desktop"), exist_ok=True)
    os.makedirs(os.path.join(STAGE_DIR, "etc/systemd/system"), exist_ok=True)

    for src, rel in [
        ("/var/www/html/index.php", "usr/share/alfred-ota/noc_index.php"),
        ("/var/www/apps/index.php", "var/www/apps/index.php"),
        ("/var/www/apps/searxng/index.php", "var/www/apps/searxng/index.php"),
        ("/var/www/apps/bigbluebutton/index.php", "var/www/apps/bigbluebutton/index.php"),
        ("/usr/local/bin/alfred-seed-server-row.py", "usr/local/bin/alfred-seed-server-row.py"),
        ("/usr/local/bin/alfred-open-cloud-controller", "usr/local/bin/alfred-open-cloud-controller"),
        ("/usr/share/applications/alfred-cloud-controller.desktop", "usr/share/applications/alfred-cloud-controller.desktop"),
        ("/etc/skel/Desktop/Alfred Sovereign Cloud Controller.desktop", "etc/skel/Desktop/Alfred Sovereign Cloud Controller.desktop"),
        ("/etc/systemd/system/alfred-sysadmin-agent.service", "etc/systemd/system/alfred-sysadmin-agent.service"),
        ("/usr/local/bin/alfred-ensure-virtual-display.sh", "usr/local/bin/alfred-ensure-virtual-display.sh"),
        ("/etc/systemd/system/alfred-virtual-display.service", "etc/systemd/system/alfred-virtual-display.service"),
        ("/usr/lib/firmware/edid/1920x1080.bin", "usr/lib/firmware/edid/1920x1080.bin"),
    ]:
        if os.path.isfile(src):
            dst = os.path.join(STAGE_DIR, rel)
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            shutil.copy2(src, dst)

    for extra_bin in ("alfred-kvm-input.py", "alfred-cluster-heartbeat.py", "alfred-rustdesk-shield.sh", "alfred-wayland-portal-autoshare.py", "alfred-ai-time-machine", "alfred-provision-citadel-apps.py", "alfred-zfs-snap-prune", "alfred-ha-websync", "alfred-vr-ws.js", "alfred-rebrand-ide.py"):
        src_b = os.path.join("/usr/local/bin", extra_bin)
        if os.path.exists(src_b):
            shutil.copy2(src_b, os.path.join(STAGE_DIR, "usr/local/bin", extra_bin))
            os.chmod(os.path.join(STAGE_DIR, "usr/local/bin", extra_bin), 0o755)

    for extra_unit in ("alfred-cluster-heartbeat.service", "alfred-cluster-heartbeat.timer", "alfred-rustdesk-shield.service", "alfred-zfs-snap-prune.service", "alfred-zfs-snap-prune.timer", "alfred-ha-websync.service", "alfred-ha-websync.timer", "alfred-vr-ws.service"):
        src_u = os.path.join("/etc/systemd/system", extra_unit)
        if os.path.exists(src_u):
            shutil.copy2(src_u, os.path.join(STAGE_DIR, "etc/systemd/system", extra_unit))

    for f2b_rel in ("etc/fail2ban/filter.d/rustdesk-sovereign.conf", "etc/fail2ban/jail.d/rustdesk-sovereign.conf"):
        src_f = "/" + f2b_rel
        if os.path.exists(src_f):
            dst_f = os.path.join(STAGE_DIR, f2b_rel)
            os.makedirs(os.path.dirname(dst_f), exist_ok=True)
            shutil.copy2(src_f, dst_f)

    os.makedirs(os.path.join(STAGE_DIR, "etc/ssh/sshd_config.d"), exist_ok=True)
    open(os.path.join(STAGE_DIR, "etc/ssh/sshd_config.d/10-alfred.conf"), "w", encoding="utf-8").write(
        "# Alfred Sovereign Datacenter OpenSSH Hardening Configuration\n"
        "PasswordAuthentication no\nPubkeyAuthentication yes\nPermitRootLogin prohibit-password\n"
        "KbdInteractiveAuthentication no\nUsePAM yes\nX11Forwarding no\nMaxAuthTries 4\n"
    )

    os.makedirs(os.path.join(STAGE_DIR, "etc/nginx/conf.d"), exist_ok=True)
    open(os.path.join(STAGE_DIR, "etc/nginx/conf.d/alfred-pqc-tls.conf"), "w", encoding="utf-8").write(
        "# Alfred Sovereign Datacenter - Post-Quantum Cryptography (PQC) TLS 1.3 Configuration\n"
        "ssl_conf_command Curves X25519MLKEM768:SecP384r1MLKEM1024:SecP256r1MLKEM768/X25519:secp384r1:prime256v1;\n"
    )

    # ALFRED_DC_IDE_EXT_BUNDLING
    ide_src_dir = "/opt/alfred-ide/extensions-bundled/gositeme.alfred-commander-5.1.0"
    if os.path.isdir(ide_src_dir):
        ide_dst_dir = os.path.join(STAGE_DIR, "opt/alfred-ide/extensions-bundled/alfred.alfred-commander-5.1.0")
        os.makedirs(ide_dst_dir, exist_ok=True)
        for fn in ("extension.js", "agent-engine.js", "package.json"):
            sf = os.path.join(ide_src_dir, fn)
            if os.path.isfile(sf):
                shutil.copy2(sf, os.path.join(ide_dst_dir, fn))

    staged_dcu = os.path.join(STAGE_DIR, "usr/local/bin/alfred-datacenter-update")
    if os.path.exists(staged_dcu):
        shutil.move(staged_dcu, os.path.join(STAGE_DIR, "usr/share/alfred-ota/alfred-datacenter-update.new"))

    postinst_sh = """#!/usr/bin/env bash
# Cumulative Post-Install Self-Healer for Alfred Linux Datacenter & Control Panel OTA v2
chmod 4755 /usr/bin/sudo /usr/bin/passwd /usr/bin/su /usr/bin/chsh /usr/bin/chfn /usr/bin/gpasswd /usr/bin/newgrp /usr/bin/pkexec /usr/lib/polkit-1/polkit-agent-helper-1 /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/openssh/ssh-keysign 2>/dev/null || true
chown root:shadow /usr/sbin/unix_chkpwd /etc/shadow /etc/gshadow 2>/dev/null || true
chmod 2755 /usr/sbin/unix_chkpwd 2>/dev/null || true
chmod 0640 /etc/shadow /etc/gshadow 2>/dev/null || true
chown -R ispconfig:ispconfig /usr/local/ispconfig/interface/web 2>/dev/null || true
chown -R root:ispconfig /usr/local/ispconfig/security /usr/local/ispconfig/extensions 2>/dev/null || true
chmod 0750 /usr/local/ispconfig/security 2>/dev/null || true
chmod 0640 /usr/local/ispconfig/security/*.alfenc /usr/local/ispconfig/security/security_settings.ini 2>/dev/null || true
chmod 0755 /usr/local/bin/alfred-license-guard /usr/local/lib/alfred-ota/chain_engine.py /usr/local/libexec/alfred-update-apply 2>/dev/null || true
ln -sf /usr/local/bin/alfred-ota-updater /usr/local/bin/alfred-update 2>/dev/null || true
systemctl daemon-reload 2>/dev/null || true
systemctl enable --now alfred-zfs-snap-prune.timer 2>/dev/null || true
if [ -f /etc/alfred-datacenter-version ]; then
    _dcv="$(tr -d '\r\n' < /etc/alfred-datacenter-version)"
    for _if in /etc/issue /etc/issue.net; do
        [ -f "$_if" ] && sed -i -E "s/Datacenter Edition v[0-9.]+/Datacenter Edition v${_dcv}/g" "$_if" 2>/dev/null || true
    done
fi
# ALFRED_DC_IDE_EXT_SELFHEAL
python3 - << 'PYDCIDE' 2>/dev/null || true
import glob, json, os, shutil
src = "/opt/alfred-ide/extensions-bundled/alfred.alfred-commander-5.1.0"
if not os.path.isdir(src):
    cands = sorted(d for d in glob.glob("/opt/alfred-ide/extensions-bundled/*alfred-commander-5*") if os.path.isdir(d))
    src = cands[0] if cands else ""
if src and os.path.isdir(src):
    src_pkg = json.load(open(os.path.join(src, "package.json"), encoding="utf-8"))
    for pat in (
        "/opt/alfred-ide/extensions-bundled/*alfred-commander-5*",
        "/var/lib/alfred-ide-admin/extensions/*alfred-commander*",
        "/var/lib/alfred-ide-users/*/extensions/*alfred-commander*",
        "/home/*/.local/share/code-server/extensions/*alfred-commander*",
        "/root/.local/share/code-server/extensions/*alfred-commander*",
    ):
        for d in glob.glob(pat):
            if not os.path.isdir(d) or ".bak" in d or os.path.abspath(d) == os.path.abspath(src):
                continue
            for fn in ("agent-engine.js", "extension.js"):
                sf = os.path.join(src, fn)
                if os.path.isfile(sf):
                    shutil.copy2(sf, os.path.join(d, fn))
            pfp = os.path.join(d, "package.json")
            cur = json.load(open(pfp, encoding="utf-8")) if os.path.isfile(pfp) else {}
            merged = dict(src_pkg)
            if cur.get("publisher"): merged["publisher"] = cur["publisher"]
            if cur.get("name"): merged["name"] = cur["name"]
            open(pfp, "w", encoding="utf-8").write(json.dumps(merged, indent=2) + "\n")
    ext_root = "/var/lib/alfred-ide-admin/extensions"
    if os.path.isdir(ext_root):
        dirs = sorted(d for d in glob.glob(os.path.join(ext_root, "*alfred-commander*")) if os.path.isdir(d))
        if len(dirs) > 1:
            keep = ([d for d in dirs if os.path.basename(d).startswith("alfred.")] or [dirs[0]])[0]
            for d in dirs:
                if d != keep:
                    shutil.rmtree(d, ignore_errors=True)
            dirs = [keep]
        if dirs:
            keep = dirs[0]
            rel = os.path.basename(keep)
            pkg = json.load(open(os.path.join(keep, "package.json"), encoding="utf-8"))
            pub, nm, ver = pkg.get("publisher", "alfred"), pkg.get("name", "alfred-commander"), pkg.get("version", "5.1.0")
            entry = [{"identifier": {"id": f"{pub}.{nm}"}, "version": ver, "location": {"$mid": 1, "fsPath": keep, "external": "file://" + keep, "path": keep, "scheme": "file"}, "relativeLocation": rel}]
            open(os.path.join(ext_root, "extensions.json"), "w", encoding="utf-8").write(json.dumps(entry))
PYDCIDE
if [ -d /var/lib/alfred-ide-admin/extensions ]; then
    if id alfred-ide-admin >/dev/null 2>&1; then chown -R alfred-ide-admin:alfred-ide-admin /var/lib/alfred-ide-admin/extensions 2>/dev/null || true
    elif id alfred >/dev/null 2>&1; then chown -R alfred:alfred /var/lib/alfred-ide-admin/extensions 2>/dev/null || true
    fi
fi
if [ -f /usr/local/bin/alfred-seed-server-row.py ]; then
    python3 /usr/local/bin/alfred-seed-server-row.py 2>/dev/null || true
fi
nginx -t >/dev/null 2>&1 && systemctl reload nginx 2>/dev/null || true
systemd-run --unit="alfred-ota-restart-$(date +%s)" /bin/sh -c "sleep 2 && (if [ -f /usr/share/alfred-ota/alfred-datacenter-update.new ]; then mv -f /usr/share/alfred-ota/alfred-datacenter-update.new /usr/local/bin/alfred-datacenter-update && chmod 755 /usr/local/bin/alfred-datacenter-update; fi) && systemctl reload-or-restart php8.4-fpm nginx && systemctl restart alfred-ide-portal alfred-sysadmin-agent" >/dev/null 2>&1 || true
"""
    postinst_path = os.path.join(STAGE_DIR, "postinst.sh")
    open(postinst_path, "w", encoding="utf-8").write(postinst_sh)
    os.chmod(postinst_path, 0o755)

    # 3. Mandatory Zero-PII & Secret Scanner
    violations = run_pii_scan(STAGE_DIR)
    if violations:
        shutil.rmtree(STAGE_DIR, ignore_errors=True)
        res = {
            "status": "error",
            "code": "PII_VIOLATION",
            "message": f"Zero-PII Gate blocked OTA build: {len(violations)} private string violation(s) found.",
            "violations": violations[:20],
        }
        print(json.dumps(res, indent=None if args.json else 2))
        sys.exit(1)

    if args.scan_only:
        shutil.rmtree(STAGE_DIR, ignore_errors=True)
        res = {
            "status": "ok",
            "zero_pii_verified": True,
            "violations": [],
            "message": "100% Zero-PII Verified! Staged Control Panel, Vaults & Sysadmin Agent contain 0 private strings.",
        }
        print(json.dumps(res, indent=None if args.json else 2))
        sys.exit(0)

    # 4. Determine next versions & preserve existing releases[] chains!
    cur_manifest = {}
    if os.path.exists(MANIFEST_PATH):
        try:
            cur_manifest = json.load(open(MANIFEST_PATH, "r", encoding="utf-8"))
        except Exception:
            cur_manifest = {}

    ver = ce.normalize_version(args.version)
    if not ver:
        old_v = ce.normalize_version(cur_manifest.get("latest") or cur_manifest.get("version") or "1.3.10")
        parts = old_v.split(".")
        ver = f"{parts[0]}.{parts[1]}.{int(parts[2]) + 1}" if (len(parts) == 3 and parts[2].isdigit()) else "1.3.11"

    panel_ver = ce.normalize_version(args.panel_version)
    if not panel_ver:
        old_pv = ce.normalize_version(cur_manifest.get("panel_version") or "31.0.14")
        pp = old_pv.split(".")
        panel_ver = f"{pp[0]}.{pp[1]}.{int(pp[2]) + 1}" if (len(pp) == 3 and pp[2].isdigit()) else f"31.0.{ver.split('.')[-1]}"

    open(os.path.join(STAGE_DIR, "etc/alfred-datacenter-version"), "w", encoding="utf-8").write(ver + "\n")
    open(os.path.join(STAGE_DIR, "etc/alfred-panel-version"), "w", encoding="utf-8").write(panel_ver + "\n")
    open("/etc/alfred-datacenter-version", "w", encoding="utf-8").write(ver + "\n")
    open("/etc/alfred-panel-version", "w", encoding="utf-8").write(panel_ver + "\n")

    os.makedirs(BUNDLES_DIR, exist_ok=True)
    bundle_name = f"alfred-dc-ota-v{ver}.tar.gz"
    bundle_path = os.path.join(BUNDLES_DIR, bundle_name)

    with tarfile.open(bundle_path, "w:gz") as tar:
        tar.add(STAGE_DIR, arcname=".")
    shutil.rmtree(STAGE_DIR, ignore_errors=True)

    sha256_hash = ce.sha256_file(bundle_path)
    bundle_size = os.path.getsize(bundle_path)
    now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    bundle_url = f"https://alfredlinux.com/api/ota-datacenter.php?action=download&file={bundle_name}"
    notes = args.notes.strip() or (
        f"Alfred Linux Datacenter & Sovereign Cloud Control Panel v{ver} (Panel v{panel_ver}): "
        "v2 Cumulative Sequential Catch-Up OTA Engine, Encrypted AES-256-GCM Vaults & Zero-PII Hardening."
    )

    # Append to Datacenter releases[] chain
    dc_releases = [
        r for r in (cur_manifest.get("releases") or [])
        if ce.normalize_version(r.get("version")) != ver
    ]
    new_dc_rel = {
        "version": ver,
        "panel_version": panel_ver,
        "url": bundle_url,
        "sha256": sha256_hash,
        "size": bundle_size,
        "kind": args.kind,
        "min_from_version": ce.normalize_version(args.min_from_version) or "1.0.0",
        "covers_from": ce.normalize_version(args.covers_from) if args.kind == "cumulative" and args.covers_from else "",
        "reboot_required": bool(args.reboot_required),
        "released_at": now_iso,
        "notes": notes,
    }
    if os.path.isfile(SECRET_KEY_PATH):
        new_dc_rel["sig"] = ce.sign_release_entry("datacenter", new_dc_rel, SECRET_KEY_PATH)
    dc_releases.append(new_dc_rel)
    dc_releases.sort(key=lambda r: ce.vtuple(r["version"]))

    dc_payload = {
        "schema_version": 2,
        "stream": "datacenter",
        "channel": "datacenter",
        "version": ver,
        "latest": dc_releases[-1]["version"],
        "panel_version": panel_ver,
        "released_at": now_iso,
        "built_at": now_iso,
        "bundle_name": bundle_name,
        "bundle_url": bundle_url,
        "url": bundle_url,
        "bundle_sha256": sha256_hash,
        "sha256": sha256_hash,
        "bundle_size": bundle_size,
        "size": bundle_size,
        "size_bytes": bundle_size,
        "zero_pii_verified": True,
        "min_kernel": "6.1.0",
        "requires_reboot": bool(args.reboot_required),
        "notes": notes,
        "features": cur_manifest.get("features") or [],
        "releases": dc_releases,
    }
    dc_manifest = ce.sign_manifest(dc_payload, SECRET_KEY_PATH, PUB_KEY_PATH) if os.path.isfile(SECRET_KEY_PATH) else dc_payload
    with open(MANIFEST_PATH + ".tmp", "w", encoding="utf-8") as f:
        json.dump(dc_manifest, f, indent=2, ensure_ascii=False)
        f.write("\n")
    os.replace(MANIFEST_PATH + ".tmp", MANIFEST_PATH)

    # Also update Control Panel stream manifest (/ota/panel/manifest.json)
    os.makedirs(PANEL_OTA_DIR, exist_ok=True)
    cur_panel = {}
    if os.path.exists(PANEL_MANIFEST_PATH):
        try:
            cur_panel = json.load(open(PANEL_MANIFEST_PATH, "r", encoding="utf-8"))
        except Exception:
            cur_panel = {}
    panel_releases = [
        r for r in (cur_panel.get("releases") or [])
        if ce.normalize_version(r.get("version")) != panel_ver
    ]
    new_panel_rel = {
        "version": panel_ver,
        "dc_version": ver,
        "panel_version": panel_ver,
        "url": bundle_url,
        "sha256": sha256_hash,
        "size": bundle_size,
        "kind": args.kind,
        "min_from_version": "0.0.0",
        "covers_from": ce.normalize_version(args.covers_from) if args.kind == "cumulative" and args.covers_from else "",
        "reboot_required": False,
        "released_at": now_iso,
        "notes": notes,
    }
    if os.path.isfile(SECRET_KEY_PATH):
        new_panel_rel["sig"] = ce.sign_release_entry("panel", new_panel_rel, SECRET_KEY_PATH)
    panel_releases.append(new_panel_rel)
    panel_releases.sort(key=lambda r: ce.vtuple(r["version"]))

    panel_payload = {
        "schema_version": 2,
        "stream": "panel",
        "channel": "panel",
        "version": panel_ver,
        "latest": panel_releases[-1]["version"],
        "panel_version": panel_ver,
        "dc_version": ver,
        "released_at": now_iso,
        "bundle_name": bundle_name,
        "bundle_url": bundle_url,
        "url": bundle_url,
        "bundle_sha256": sha256_hash,
        "sha256": sha256_hash,
        "bundle_size": bundle_size,
        "size": bundle_size,
        "zero_pii_verified": True,
        "requires_reboot": False,
        "notes": notes,
        "features": dc_payload["features"],
        "releases": panel_releases,
    }
    panel_manifest = ce.sign_manifest(panel_payload, SECRET_KEY_PATH, PUB_KEY_PATH) if os.path.isfile(SECRET_KEY_PATH) else panel_payload
    with open(PANEL_MANIFEST_PATH + ".tmp", "w", encoding="utf-8") as f:
        json.dump(panel_manifest, f, indent=2, ensure_ascii=False)
        f.write("\n")
    os.replace(PANEL_MANIFEST_PATH + ".tmp", PANEL_MANIFEST_PATH)

    res = {
        "status": "ok",
        "schema_version": 2,
        "version": ver,
        "panel_version": panel_ver,
        "bundle_name": bundle_name,
        "bundle_path": bundle_path,
        "bundle_sha256": sha256_hash,
        "bundle_size": bundle_size,
        "dc_chain_length": len(dc_releases),
        "panel_chain_length": len(panel_releases),
        "signed": os.path.isfile(SECRET_KEY_PATH),
        "zero_pii_verified": True,
        "message": f"Built & published signed v2 Zero-PII OTA bundle {bundle_name} ({bundle_size // 1024} KB, DC chain={len(dc_releases)}, Panel chain={len(panel_releases)})!",
    }
    print(json.dumps(res, indent=None if args.json else 2))


if __name__ == "__main__":
    main()
