#!/usr/bin/env python3
"""Refresh tools/fixtures/lineage-24.0 from a LineageOS 24.0 tree (default build/l24).

The fixture is the smallest slice of the real tree that every check in
tools/check.sh reads: the files that define a name Vanta overlays, the
Lineage hooks and modules Vanta relies on, the brand strings, and the
recovery art Vanta replaces. Files are copied verbatim, never edited, so a
check that passes on the fixture passed on real Lineage source.
"""
import glob
import os
import re
import shutil
import sys

HERE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SRC = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "build/l24")
DST = os.path.join(HERE, "tools/fixtures/lineage-24.0")

FIXED = [
    "vendor/lineage/config/common.mk",
    "vendor/lineage/config/BoardConfigReservedSize.mk",
    "vendor/lineage/config/common_full_phone.mk",
    "vendor/lineage/build/target/product/lineage_gsi_arm64.mk",
    "vendor/lineage/build/target/product/lineage_generic_target.mk",
    "vendor/lineage/config/version.mk",
    "vendor/lineage/bootanimation/Android.bp",
    "vendor/lineage/vars/aosp_target_release",
    "packages/overlays/Lineage/fonts/etc/Android.bp",
    "packages/overlays/Lineage/fonts/etc/fonts_customization.xml",
    "packages/apps/Updater/app/Android.bp",
    "packages/apps/SetupWizard/app/Android.bp",
    "lineage-sdk/lineage/res/AndroidManifest.xml",
    "packages/apps/LineageParts/AndroidManifest.xml",
    "packages/apps/Launcher3/quickstep/AndroidManifest.xml",
    "packages/apps/Settings/src/com/android/settings/gestures/SystemNavigationGestureSettings.java",
    "packages/apps/Settings/src/com/android/settings/gestures/SystemNavigationPreferenceController.java",
    "frameworks/base/packages/overlays/NavigationBarMode3ButtonOverlay/Android.bp",
    "frameworks/base/packages/overlays/NavigationBarMode2ButtonOverlay/Android.bp",
]
TARGET_ROOTS = [
    "frameworks/base/core/res/res",
    "frameworks/base/packages/SettingsProvider/res",
    "packages/apps/Settings/res",
    "frameworks/base/packages/SettingsLib/SettingsTheme/res",
    "frameworks/base/packages/SettingsLib/res",
    "packages/apps/Launcher3/res",
    "packages/apps/Launcher3/quickstep/res",
]
NAME = re.compile(r'name="([^"]+)"')


def copy(rel):
    s, d = os.path.join(SRC, rel), os.path.join(DST, rel)
    if not os.path.exists(s):
        sys.exit(f"refresh_l24: missing {rel}")
    os.makedirs(os.path.dirname(d), exist_ok=True)
    shutil.copy2(s, d)


def main():
    if os.path.isdir(DST):
        shutil.rmtree(DST)
    for rel in FIXED:
        copy(rel)
    wanted = set()
    # Only the overlays verify_tree checks against these roots; the brand RROs
    # target Lineage packages and are covered by the string copy below.
    for f in glob.glob(os.path.join(HERE, "vendor/vanta/overlay/*/res/**/*.xml"), recursive=True):
        if "/VantaBrand" in f or "/FontIBMPlexSansOverlay/" in f:
            continue
        wanted |= set(NAME.findall(open(f, errors="replace").read()))
        wanted.add(os.path.basename(f)[:-4])
    n = 0
    for root in TARGET_ROOTS:
        for f in glob.glob(os.path.join(SRC, root, "*", "*.xml")):
            dirname = os.path.basename(os.path.dirname(f))
            kind = dirname.split("-")[0]
            if not all(q == "night" or re.fullmatch(r"v\d+", q) for q in dirname.split("-")[1:]):
                continue  # verify_tree only weighs night/vNN variants
            text = open(f, errors="replace").read()
            hit = (kind in ("color", "drawable", "layout") and os.path.basename(f)[:-4] in wanted) or \
                  (kind == "values" and wanted & set(NAME.findall(text)))
            if hit:
                copy(os.path.relpath(f, SRC)); n += 1
    # Brand strings: every locale of the two string files the brand RROs rewrite.
    for pat in ("lineage-sdk/lineage/res/res/values*/strings.xml", "packages/apps/LineageParts/res/values*/strings.xml"):
        for f in glob.glob(os.path.join(SRC, pat)):
            copy(os.path.relpath(f, SRC)); n += 1
    # Recovery art Vanta replaces (gen_recovery --check reads their sizes).
    for f in glob.glob(os.path.join(SRC, "bootable/recovery/res-*dpi/images/*.png")):
        b = os.path.basename(f)
        if b in ("logo_image.png", "logo_image_switch.png", "fastbootd.png", "loop00000.png", "progress_fill.png"):
            copy(os.path.relpath(f, SRC)); n += 1
    copy("bootable/recovery/recovery.cpp")
    copy("bootable/recovery/recovery_ui/screen_ui.cpp")
    open(os.path.join(DST, "SOURCE"), "w").write(
        "LineageOS lineage-24.0 (android-17.0.0_r1), copied verbatim by tools/fixtures/refresh_l24.py\n"
        f"from {os.path.relpath(SRC, HERE)}: {len(FIXED)} fixed files + {n} resource/string/art files.\n")
    print(f"refresh_l24: {len(FIXED)} fixed + {n} files -> {os.path.relpath(DST, HERE)}")


if __name__ == "__main__":
    main()
