#!/usr/bin/env python3
"""Generate the brand RROs that rename LineageOS to Vanta wherever a user reads it.

The strings are taken from the synced LineageOS 24.0 tree, in every locale the
tree translates them into, and rewritten in place ("LineageOS" / "Lineage" ->
"Vanta"). Generating from the translations rather than writing English strings
is the point: an RRO's values/ entry loses to the target's values-en-rGB/ one,
so an English-only overlay would leave "LineageOS version" on an en-GB phone.

Left alone on purpose: the statistics strings (the data still goes to
LineageOS's servers, so they must keep naming them) and Settings' legal entry
(attribution for the base).

Usage: tools/gen_branding.py [--src TREE] [--check]
  --src    source root holding lineage-sdk and packages/apps/LineageParts
           (default build/l24, the reference clone on Zo)
  --check  regenerate in memory and fail if the committed overlays differ
"""
import argparse
import glob
import os
import re
import sys

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(HERE, "vendor/vanta/overlay")

TARGETS = {
    "VantaBrandPlatformOverlay": {
        "package": "com.failure.vanta.overlay.brand.platform",
        "target": "lineageos.platform",
        "res": "lineage-sdk/lineage/res/res",
        "names": ["lineageos_system_label", "permdesc_useHardwareFramework",
                  "permlab_writeSettings", "permdesc_writeSettings",
                  "permlab_writeSecureSettings", "permdesc_writeSecureSettings",
                  "lineage_api_level", "lineage_updates", "lineage_version"],
    },
    "VantaBrandPartsOverlay": {
        "package": "com.failure.vanta.overlay.brand.parts",
        "target": "org.lineageos.lineageparts",
        "res": "packages/apps/LineageParts/res",
        "names": ["lineageparts_title", "privacy_settings_category", "egg_title",
                  "trust_feature_security_patches_explain"],
    },
}

HEADER = "<!-- GENERATED by tools/gen_branding.py from the LineageOS 24.0 tree. Do not edit. -->\n"
STRING_RE = re.compile(r'<string\s+name="([^"]+)"([^>]*)>(.*?)</string>', re.S)


def rebrand(text):
    return re.sub(r"Lineage(?:OS)?", "Vanta", text)


def locale_dir(d):
    """values or values-<locale>; None for anything carrying other qualifiers."""
    base = os.path.basename(d)
    if base == "values":
        return base
    q = base[len("values-"):] if base.startswith("values-") else None
    if q and re.fullmatch(r"[a-z]{2,3}(-r[A-Z]{2})?|b\+[A-Za-z0-9+]+", q):
        return base
    return None


def build(src):
    files = {}
    for ov, t in TARGETS.items():
        res = os.path.join(src, t["res"])
        if not os.path.isdir(res):
            raise SystemExit(f"gen_branding: missing {res}")
        found_default = set()
        for d in sorted(glob.glob(os.path.join(res, "values*"))):
            loc = locale_dir(d)
            if not loc:
                continue
            got = {}
            for f in sorted(glob.glob(os.path.join(d, "*.xml"))):
                for name, attrs, body in STRING_RE.findall(open(f, encoding="utf-8").read()):
                    if name in t["names"] and name not in got:
                        attrs = re.sub(r'\s*translatable="false"', "", attrs)
                        got[name] = (attrs, body)
            if not got:
                continue
            if loc == "values":
                found_default = set(got)
            lines = [f'    <string name="{n}"{a}>{rebrand(b)}</string>' for n, (a, b) in
                     sorted(got.items())]
            files[f"{ov}/res/{loc}/vanta_brand.xml"] = (
                '<?xml version="1.0" encoding="utf-8"?>\n' + HEADER + "<resources>\n"
                + "\n".join(lines) + "\n</resources>\n")
        missing = set(t["names"]) - found_default
        if missing:
            raise SystemExit(f"gen_branding: {t['target']} no longer defines {sorted(missing)}")
        files[f"{ov}/AndroidManifest.xml"] = (
            '<?xml version="1.0" encoding="utf-8"?>\n' + HEADER
            + '<manifest xmlns:android="http://schemas.android.com/apk/res/android"\n'
            + f'    package="{t["package"]}">\n'
            + f'    <overlay android:targetPackage="{t["target"]}" android:isStatic="true" android:priority="900" />\n'
            + '    <application android:hasCode="false" />\n</manifest>\n')
    return files


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", default=os.path.join(HERE, "build/l24"))
    ap.add_argument("--check", action="store_true")
    a = ap.parse_args()
    want = build(a.src)
    have = {}
    for ov in TARGETS:
        for p in glob.glob(os.path.join(OUT, ov, "**/*"), recursive=True):
            if os.path.isfile(p):
                have[os.path.relpath(p, OUT)] = open(p, encoding="utf-8").read()
    drift = sorted(k for k in set(want) | set(have) if want.get(k) != have.get(k))
    if a.check:
        for k in drift:
            print(f"gen_branding: drift {k}")
        print(f"gen_branding: {'DRIFT' if drift else 'ok'} ({len(want)} files)")
        return 1 if drift else 0
    for k in drift:
        p = os.path.join(OUT, k)
        if k in want:
            os.makedirs(os.path.dirname(p), exist_ok=True)
            open(p, "w", encoding="utf-8").write(want[k])
        else:
            os.remove(p)
    print(f"gen_branding: wrote {len(drift)} of {len(want)} files")
    return 0


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