#!/usr/bin/env python3
"""Lay the Vanta layer onto the LineageOS 23.2 beyond2lte trees for a 24.0 build.

The base is LineageOS lineage-24.0 (android-17.0.0_r1), so the product stays
`lineage_beyond2lte` and inherits vendor/lineage unchanged; the device trees
only stop at 23.2 because nobody has branched them for 24.0 yet. What this adds
is the Vanta board config and the one telephony overlay line.

Applied by tools/apply.sh to the checked-out trees after every `repo sync`.
Idempotent: running it twice is the same as once, and --check reports what it
*would* change without writing, which is how tools/check.sh proves it against
real clones of the pinned commits.

Every edit is anchored on an exact string. If an anchor is missing the run
fails loudly -- a silent miss is the failure mode this script exists to stop.
"""
import argparse
import os
import sys

class Miss(Exception):
    pass


def sub(text, old, new, what):
    if new in text and old not in text:
        return text  # already applied
    if old not in text:
        raise Miss(f"{what}: anchor not found: {old!r}")
    return text.replace(old, new)


def device(root):
    """device/samsung/beyond2lte"""
    edits = {}
    ap = os.path.join(root, "AndroidProducts.mk")
    ok = "lineage_beyond2lte.mk" in open(ap).read()
    if not ok:
        raise Miss("AndroidProducts: lineage_beyond2lte.mk no longer registered")

    # Marketing props carry spaces, which PRODUCT_*_PROPERTIES splits on, so
    # they live in a prop file merged into system/build.prop.
    bc = os.path.join(root, "BoardConfig.mk")
    t = open(bc).read()
    lines = ["TARGET_SYSTEM_PROP += vendor/vanta/props/system.prop",
             # kernel/vanta.config: KernelSU-Next, merged after the defconfig
             "TARGET_KERNEL_CONFIG += vanta.config"]
    if lines[0] not in t:
        t = t.rstrip("\n") + "\n\n# Vanta\n" + "\n".join(lines) + "\n"
    edits[bc] = t

    # The one telephony-relevant device difference between Infinity 3.12
    # (mobile data works) and LineageOS 23.2 (it does not): the radio HAL
    # declares slot1+slot2 on both, but only Infinity tells the framework the
    # phone has two physical slots. ril/README.md has the full diff.
    ov = os.path.join(root, "overlay/frameworks/base/core/res/res/values/config.xml")
    t = open(ov).read()
    if "config_num_physical_slots" not in t:
        t = sub(t, "</resources>",
                "    <!-- Vanta: SM-G975F is dual-SIM; matches Infinity X 3.12 -->\n"
                "    <integer name=\"config_num_physical_slots\">2</integer>\n</resources>",
                "physical slots overlay")
    edits[ov] = t
    return edits


def common(root):
    """device/samsung/exynos9820-common: two Android 17 source moves the 23.2
    tree predates. Its reserved-size include must also still resolve (it is
    -include'd, so a moved file would build fine and silently drop the
    reserved sizes)."""
    edits = {}
    bc = open(os.path.join(root, "BoardConfigCommon.mk")).read()
    if "-include vendor/lineage/config/BoardConfigReservedSize.mk" not in bc:
        raise Miss("BoardConfigCommon: reserved-size include moved")

    mk = os.path.join(root, "common.mk")
    t = open(mk).read()
    # 17 gives pixel's power and thermal HALs their own soong_namespace, so
    # exporting hardware/google/pixel no longer reaches them and Kati reports
    # the power/thermal services and thermal_symlinks as non-existent.
    if "hardware/google/pixel/thermal" not in t:
        t = sub(t, "    hardware/google/pixel \\\n",
                "    hardware/google/pixel \\\n"
                "    hardware/google/pixel/power-libperfmgr \\\n"
                "    hardware/google/pixel/thermal \\\n",
                "pixel sub-namespaces")
    # 17 deletes hardware/interfaces/configstore outright, so the service that
    # switched the HIDL configstore off has nothing left to switch off.
    t = sub(t, "# ConfigStore\nPRODUCT_PACKAGES += \\\n    disable_configstore\n\n", "",
            "configstore package")
    edits[mk] = t

    # 17 declares sysfs_block in public platform policy, so the tree's own
    # declaration is a duplicate and checkpolicy stops the vendor policy build.
    # Keep the platform type and attach only the vendor attribute it lacks.
    fte = os.path.join(root, "sepolicy/vendor/file.te")
    edits[fte] = sub(open(fte).read(),
                     "type sysfs_block, sysfs_type, r_fs_type, fs_type;\n",
                     "typeattribute sysfs_block r_fs_type;\n",
                     "sysfs_block declaration")
    return edits


def run(dev_root, common_root, check):
    changed = []
    try:
        d_edits = device(dev_root)
        c_edits = common(common_root)
    except Miss as e:
        print(f"uprev: FAIL {e}", file=sys.stderr)
        return 2
    for path, text in {**d_edits, **c_edits}.items():
        cur = open(path).read() if os.path.exists(path) else None
        if cur != text:
            changed.append(path)
            if not check:
                open(path, "w").write(text)
    for c in changed:
        print(("would change " if check else "changed ") + c)
    if not changed:
        print("uprev: already applied")
    return 0


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--tree", required=True, help="Android source root")
    ap.add_argument("--check", action="store_true")
    a = ap.parse_args()
    sys.exit(run(os.path.join(a.tree, "device/samsung/beyond2lte"),
                 os.path.join(a.tree, "device/samsung/exynos9820-common"), a.check))
