#!/usr/bin/env bash
# Everything about Vanta that can be proven without a build box or the phone.
# Every gate here is also shown to FAIL on an injected fault: a check that
# cannot fail is not a check.
set -uo pipefail
P=$(cd "$(dirname "$0")/.." && pwd)
cd "$P" || exit 1
SDK=${ANDROID_SDK:-/opt/android-sdk}
AAPT2=$(ls "$SDK"/build-tools/*/aapt2 2>/dev/null | sort -V | tail -1)
JAR=$(ls "$SDK"/platforms/android-*/android.jar 2>/dev/null | sort -V | tail -1)
W=$(mktemp -d)
export GATE_OUT="$W/gate-out"
pass=0; fail=0
ok() { if [ "$1" = 0 ]; then pass=$((pass+1)); echo "ok    $2"; else fail=$((fail+1)); echo "FAIL  $2"; fi; }
run() { local d=$1; shift; "$@" >"$W/last.log" 2>&1; ok $? "$d"; }
grep -q 'ulimit -n "$(ulimit -Hn)"' tools/host-run.sh; ok $? "host-run raises the fd soft limit (soong EMFILE at analysis)"
neg() { local d=$1; shift; if "$@" >"$W/last.log" 2>&1; then ok 1 "$d"; else ok 0 "$d"; fi; }
grep -q 'fdprobe.py' tools/host-run.sh; ok $? "host-run probes host file handles before sync and build"
python3 tools/fdprobe.py /usr 2000 >/dev/null 2>&1; ok $? "fdprobe passes on a healthy host"
bash -c 'ulimit -n 64; python3 tools/fdprobe.py /usr 2000' >/dev/null 2>&1; [ $? -ne 0 ]; ok $? "fdprobe fails when file handles run out"

echo "== scripts"
for s in tools/*.sh kernel/*.sh tools/fake/bin/adb; do run "shellcheck $s" shellcheck -S warning "$s"; done
for s in device/uprev.py tools/gen_overlays.py tools/verify_tree.py tools/gen_branding.py tools/gen_fonts.py tools/gen_recovery.py tools/fixtures/refresh_l24.py tools/bootanim/make.py; do run "python compiles $s" python3 -m py_compile "$s"; done

echo "== manifest"
run "local manifest is well-formed XML" python3 -c "import xml.dom.minidom as m; m.parse('manifest/vanta.xml')"
run "device-specific repos are pinned by SHA" python3 - <<'EOF'
import re, sys
t = open("manifest/vanta.xml").read()
for path in ("device/samsung/beyond2lte", "device/samsung/exynos9820-common", "kernel/samsung/exynos9820",
             "vendor/samsung/beyond2lte", "vendor/samsung/exynos9820-common"):
    m = re.search(r'path="%s"[^>]*revision="([0-9a-f]{40})"' % re.escape(path), t, re.S)
    if not m: sys.exit(f"{path} not pinned")
EOF
run "manifest never claims vendor/extra or vendor/vanta" bash -c "! grep -E 'path=\"vendor/(extra|vanta)\"' manifest/vanta.xml"

echo "== device uprev (real lineage-23.2 device trees on a real lineage-24.0 slice)"
mk_tree() { # a synthetic source root assembled from the committed fixtures
  local T=$1 F=tools/fixtures
  mkdir -p "$T/device/samsung" "$T/.repo" "$T/build" \
           "$T/kernel/samsung/exynos9820/drivers" "$T/kernel/samsung/exynos9820/arch/arm64/configs"
  cp -r "$F/lineage-24.0/." "$T/"   # verbatim LineageOS 24.0 files (refresh_l24.py)
  rm -f "$T/SOURCE"
  cp -r "$F/lineage-23.2/beyond2lte" "$T/device/samsung/beyond2lte"
  cp -r "$F/lineage-23.2/exynos9820-common" "$T/device/samsung/exynos9820-common"
  printf 'vendor/lineage\ndevice/samsung/beyond2lte\n' > "$T/.repo/project.list"
  ln -s ../KernelSU-Next/kernel "$T/kernel/samsung/exynos9820/drivers/kernelsu"
  cp kernel/vanta.config "$T/kernel/samsung/exynos9820/arch/arm64/configs/vanta.config"
  mkdir -p "$T/vendor/extra" "$T/vendor/vanta"
  cp vendor/extra/product.mk "$T/vendor/extra/"
  rsync -a --exclude prebuilt vendor/vanta/ "$T/vendor/vanta/"
  tools/recovery.sh "$T" >/dev/null
  tools/fonts.sh "$T" >/dev/null
  : > "$T/build/envsetup.sh"
}
T="$W/tree"; mk_tree "$T"
run "uprev applies to the pinned trees" python3 device/uprev.py --tree "$T"
run "uprev is idempotent (--check clean after apply)" bash -c "python3 device/uprev.py --tree '$T' --check | grep -qx 'uprev: already applied'"
run "uprev exports pixel power/thermal sub-namespaces (17 split them)" grep -q "hardware/google/pixel/thermal" "$T/device/samsung/exynos9820-common/common.mk"
neg "uprev drops disable_configstore (17 deleted configstore)" grep -q "disable_configstore" "$T/device/samsung/exynos9820-common/common.mk"
neg "uprev drops the duplicate sysfs_block type (17 declares it in public policy)" grep -q "^type sysfs_block," "$T/device/samsung/exynos9820-common/sepolicy/vendor/file.te"
run "product stays lineage_beyond2lte on vendor/lineage (no Infinity left)" bash -c "grep -q 'PRODUCT_NAME := lineage_beyond2lte' '$T/device/samsung/beyond2lte/lineage_beyond2lte.mk' && ! grep -rqE 'vendor/infinity|infinity_beyond2lte' '$T/device/samsung'"
run "device overlay still valid XML after the slot edit" python3 -c "import xml.dom.minidom as m; m.parse('$T/device/samsung/beyond2lte/overlay/frameworks/base/core/res/res/values/config.xml')"
run "kernel fragment wired into TARGET_KERNEL_CONFIG" grep -q 'TARGET_KERNEL_CONFIG += vanta.config' "$T/device/samsung/beyond2lte/BoardConfig.mk"
T2="$W/tree2"; mk_tree "$T2"; sed -i 's|lineage_beyond2lte.mk|lineage_moved.mk|' "$T2/device/samsung/beyond2lte/AndroidProducts.mk"
neg "uprev FAILS LOUDLY when the product moves" python3 device/uprev.py --tree "$T2"
T3="$W/tree3"; mk_tree "$T3"; sed -i 's|-include vendor/lineage/config/BoardConfigReservedSize.mk||' "$T3/device/samsung/exynos9820-common/BoardConfigCommon.mk"
neg "uprev FAILS on a missing -include (the silent-miss case)" python3 device/uprev.py --tree "$T3"
echo "== vendor prebuilt clash fix (Soong 'found in multiple namespaces')"
VF="$W/vendorfix"; mkdir -p "$VF/vendor/samsung/b5q" "$VF/vendor/samsung/sm8550-common"
for pair in "b5q:cc_prebuilt_library_shared:libsamsungSoundbooster_plus:soundfx/" "sm8550-common:cc_prebuilt_binary:hermesd:"; do
  IFS=: read -r D K N SUB <<<"$pair"
  { echo "$K {"; echo "    name: \"$N\","; echo "    owner: \"samsung\","; echo "    srcs: [\"proprietary/vendor/$SUB$N\"],"; echo "}"; } > "$VF/vendor/samsung/$D/Android.bp"
done
run "vendor_fix drops the prebuilt from the tree (--check first)" bash -c "python3 tools/vendor_fix.py --tree '$VF' --check | grep -q 'would drop vendor/samsung/b5q/Android.bp: libsamsungSoundbooster_plus'"
run "vendor_fix applies to a fresh synced tree" python3 tools/vendor_fix.py --tree "$VF"
run "vendor_fix is idempotent" bash -c "python3 tools/vendor_fix.py --tree '$VF' | grep -qx 'vendor_fix: already clean'"
VFSHAPED="$W/vendorfix-shaped"; mkdir -p "$VFSHAPED/vendor/samsung/b5q"
printf 'cc_prebuilt_binary {\n    name: "libsamsungSoundbooster_plus",\n}\n' > "$VFSHAPED/vendor/samsung/b5q/Android.bp"
neg "vendor_fix FAILS when the module moved shape" python3 tools/vendor_fix.py --tree "$VFSHAPED"

echo "== tree assumptions (verify_tree.py)"
run "verify_tree passes on the applied synthetic tree" python3 tools/verify_tree.py "$T" --device beyond2lte
for fault in hook claimed bootanim override fontxml clash brandpkg recovery fraction font kernel slots resname variant drawable navgate navmod; do
  TF="$W/vt-$fault"; mk_tree "$TF"; python3 device/uprev.py --tree "$TF" >/dev/null
  case $fault in
    hook)     sed -i 's|vendor/extra/product.mk|vendor/extra/product-moved.mk|' "$TF/vendor/lineage/config/common.mk" ;;
    claimed)  echo vendor/extra >> "$TF/.repo/project.list" ;;
    bootanim) sed -i 's/"prebuilt_file"/"prebuilt_gone"/' "$TF/vendor/lineage/bootanimation/Android.bp" ;;
    override) sed -i 's/name: "Updater"/name: "UpdaterMoved"/' "$TF/packages/apps/Updater/app/Android.bp" ;;
    fontxml)  cp "tools/fixtures/lineage-24.0/packages/overlays/Lineage/fonts/etc/fonts_customization.xml" "$TF/packages/overlays/Lineage/fonts/etc/" ;;
    clash)    printf 'prebuilt_etc {\n    name: "x",\n    src: "x",\n    filename: "fonts_customization.xml",\n    product_specific: true,\n}\n' >> "$TF/vendor/vanta/Android.bp" ;;
    brandpkg) sed -i 's/package="lineageos.platform"/package="lineageos.moved"/' "$TF/lineage-sdk/lineage/res/AndroidManifest.xml" ;;
    recovery) cp "tools/fixtures/lineage-24.0/bootable/recovery/res-xxhdpi/images/logo_image.png" "$TF/bootable/recovery/res-xxhdpi/images/logo_image.png" ;;
    fraction) sed -i 's/def_window_transition_scale/def_window_transition_scale_gone/' "$TF/frameworks/base/packages/SettingsProvider/res/values/defaults.xml" ;;
    font)     rm "$TF/vendor/vanta/overlay/FontIBMPlexSansOverlay/AndroidManifest.xml" ;;
    kernel)   rm "$TF/kernel/samsung/exynos9820/drivers/kernelsu" ;;
    slots)    sed -i '/config_num_physical_slots/d' "$TF/device/samsung/beyond2lte/overlay/frameworks/base/core/res/res/values/config.xml" ;;
    resname)  sed -i 's/settingslib_preference_corner_radius/settingslib_preference_corner_radius_gone/' "$TF/frameworks/base/packages/SettingsLib/SettingsTheme/res/values-v36/dimens.xml" ;;
    variant)  mkdir -p "$TF/frameworks/base/core/res/res/values-night-v99"
              printf '<resources><color name="background_floating_device_default_dark">#000</color></resources>\n' > "$TF/frameworks/base/core/res/res/values-night-v99/colors.xml" ;;
    drawable) rm "$TF/packages/apps/Launcher3/quickstep/res/drawable/overview_action_button_background.xml" ;;
    navgate)  perl -0pi -e 's/SystemNavigationPreferenceController\.isOverlayPackageAvailable\(\w+,\s*NAV_BAR_MODE_3BUTTON_OVERLAY\)/true/g' "$TF/packages/apps/Settings/src/com/android/settings/gestures/SystemNavigationGestureSettings.java" ;;
    navmod)   rm "$TF/frameworks/base/packages/overlays/NavigationBarMode2ButtonOverlay/Android.bp" ;;
  esac
  neg "verify_tree catches fault: $fault" python3 tools/verify_tree.py "$TF" --device beyond2lte
done

echo "== device profiles (devices/*.env)"
for d in devices/*.env; do
  n=$(basename "$d" .env)
  run "profile $n loads and is complete" bash -c ". tools/lib/profile.sh && VANTA_DEVICE=$n vanta_profile '$P'"
done
neg "an unknown device is refused before anything runs" bash -c ". tools/lib/profile.sh && VANTA_DEVICE=nope vanta_profile '$P'"
run "default device is the Z Flip5 (b5q)" bash -c ". tools/lib/profile.sh && unset VANTA_DEVICE && vanta_profile '$P' && [ \$VANTA_PRODUCT = lineage_b5q ]"
run "sync/apply/build read the profile and name no device themselves" bash -c "for s in tools/build.sh tools/apply.sh tools/sync.sh; do grep -q 'vanta_profile' \$s && ! grep -qE 'beyond2lte|b5q|exynos9820|sm8550' \$s || exit 1; done"
run "every manifest is well-formed XML (a -- inside a comment breaks repo)" bash -c "for m in manifest/*.xml; do python3 -c \"import xml.dom.minidom as d; d.parse('\$m')\" || exit 1; done"
run "Flip5 manifest pins are full SHAs or branches (repo reads a short SHA as a branch)" python3 - <<'EOF'
import re
t = open("manifest/vanta-zflip5.xml").read()
for path, rev in re.findall(r'path="([^"]+)"[^>]*?revision="([^"]+)"', t, re.S):
    hexy = re.fullmatch(r"[0-9a-f]+", rev)
    assert not hexy or len(rev) == 40, f"{path}: {rev} is a short SHA"
    assert not hexy or 'upstream="' in t.split(f'path="{path}"', 1)[1].split("/>", 1)[0], f"{path}: SHA pin without upstream"
EOF
run "Flip5 manifest carries both blob repos (device.mk inherits them unconditionally)" bash -c "grep -q 'path=\"vendor/samsung/b5q\"' manifest/vanta-zflip5.xml && grep -q 'path=\"vendor/samsung/sm8550-common\"' manifest/vanta-zflip5.xml"
mk_b5q() {
  mk_tree "$1"
  cp -r tools/fixtures/b5q/device/. "$1/device/"
  for f in vendor/samsung/b5q/b5q-vendor.mk vendor/samsung/sm8550-common/sm8550-common-vendor.mk \
           vendor/samsung/sm8550-common/BoardConfigVendor.mk device/samsung/sm8550-common/common.mk \
           hardware/samsung/Android.bp kernel/samsung/sm8550/arch/arm64/configs/b5q_defconfig; do
    mkdir -p "$1/$(dirname "$f")"; : > "$1/$f"
  done
}
TB5="$W/b5q"; mk_b5q "$TB5"
run "verify_tree passes on a synced Flip5 tree" python3 tools/verify_tree.py "$TB5" --device b5q
for f in vendor/samsung/b5q/b5q-vendor.mk vendor/samsung/sm8550-common/sm8550-common-vendor.mk kernel/samsung/sm8550/arch/arm64/configs/b5q_defconfig; do
  TBF="$W/b5q-$(basename "$f")"; mk_b5q "$TBF"; rm "$TBF/$f"
  neg "verify_tree catches a Flip5 tree missing $f" python3 tools/verify_tree.py "$TBF" --device b5q
done
TBL="$W/b5q-layout"; mk_b5q "$TBL"
python3 - "$TBL/device/samsung/b5q/configs/display/display_layout_configuration.xml" <<'EOF'
import re, sys
p = sys.argv[1]; t = open(p).read()
# Fault: the closed state keeps the inner panel as display 0 (no cover home at all).
close = re.search(r"<layout>\s*<state>0</state>.*?</layout>", t, re.S).group(0)
swapped = close.replace('defaultDisplay="false"', "@F@").replace('defaultDisplay="true"', 'defaultDisplay="false"').replace("@F@", 'defaultDisplay="true"')
open(p, "w").write(t.replace(close, swapped))
EOF
neg "verify_tree catches a display layout that never hands display 0 to the cover" python3 tools/verify_tree.py "$TBL" --device b5q
TG="$W/gsi"; mk_tree "$TG"
run "verify_tree passes on a GSI tree" python3 tools/verify_tree.py "$TG" --device gsi_arm64
neg "verify_tree refuses a device it does not know" python3 tools/verify_tree.py "$TG" --device nope

run "Flip5 and GSI manifests carry MindTheGapps pinned, and their profiles turn it on" python3 - <<'PY'
for m in ("manifest/vanta-zflip5.xml", "manifest/vanta-gsi.xml"):
    t = open(m).read()
    assert 'path="vendor/gapps"' in t and 'upstream="cinnamonbun"' in t, m
for d in ("b5q", "gsi_arm64"):
    assert "VANTA_GAPPS=${VANTA_GAPPS:-true}" in open(f"devices/{d}.env").read(), d
mk = open("vendor/vanta/vanta.mk").read()
assert "ifeq ($(VANTA_GAPPS),true)" in mk and "vendor/gapps/arm64/arm64-vendor.mk" in mk
assert "VANTA_GAPPS=true but vendor/gapps is not synced" in mk
PY
run "VantaWelcome replaces Google's SetupWizard, signs in to Google itself, and turns Play Protect's checks off" python3 - <<'PY'
bp = open("vendor/vanta/packages/VantaWelcome/Android.bp").read()
g = open("vendor/vanta/packages/VantaWelcome/src/com/failure/vanta/welcome/Google.kt").read()
assert '"SetupWizard"' in bp and "addAccount(ACCOUNT_TYPE" in g
for k in ("package_verifier_enable", "verifier_verify_adb_installs"):
    assert f'"{k}", 0' in g, k
assert "playProtectOff" in open("vendor/vanta/packages/VantaWelcome/src/com/failure/vanta/welcome/Setup.kt").read()
PY
run "Vanta Voice is the default assistant, above MindTheGapps' GmsOverlay (priority 1337)" python3 - <<'PY'
import re
m = open("vendor/vanta/overlay/VantaRolesOverlay/AndroidManifest.xml").read()
assert int(re.search(r'android:priority="(\d+)"', m).group(1)) > 1337
assert "com.failure.vanta.voice" in open("vendor/vanta/overlay/VantaRolesOverlay/res/values/config.xml").read()
assert "VantaRolesOverlay" in open("vendor/vanta/vanta.mk").read()
PY
TGA="$W/gapps"; mk_b5q "$TGA"
neg "verify_tree catches GApps switched on but not synced" env VANTA_GAPPS=true python3 tools/verify_tree.py "$TGA" --device b5q
mkdir -p "$TGA/vendor/gapps/arm64"; printf 'PRODUCT_PACKAGES += SetupWizard\n' > "$TGA/vendor/gapps/arm64/arm64-vendor.mk"
run "verify_tree passes with GApps synced" env VANTA_GAPPS=true python3 tools/verify_tree.py "$TGA" --device b5q

echo "== packaging (what Soong would only tell the box)"
run "every app with an Android.bp is in PRODUCT_PACKAGES" python3 - <<'EOF'
import glob, os, re
mk = open("vendor/vanta/vanta.mk").read()
for bp in glob.glob("vendor/vanta/packages/*/Android.bp"):
    for kind, name in re.findall(r'^(android_app|android_library)\s*\{\s*name:\s*"([^"]+)"', open(bp).read(), re.M):
        if kind == "android_app":
            assert re.search(rf"^\s*{name}\s*\\?$", mk, re.M), f"{name} ({bp}) is built nowhere"
EOF
run "an .xml prebuilt_etc installs under an .xml name (else PackageManager ignores it)" python3 - <<'EOF'
import glob, re
for bp in glob.glob("vendor/vanta/**/Android.bp", recursive=True):
    for body in re.findall(r"prebuilt_etc\s*\{(.*?)\n\}", open(bp).read(), re.S):
        name = re.search(r'name:\s*"([^"]+)"', body).group(1)
        src = re.search(r'src:\s*"([^"]+)"', body).group(1)
        if src.endswith(".xml") and not re.search(r"filename|filename_from_src", body):
            assert name.endswith(".xml"), f"{bp}: {name} installs without .xml"
EOF
run "optional APKs are declared by stage.sh, never in vendor/vanta/Android.bp" bash -c "! grep -q android_app_import vendor/vanta/Android.bp"
run "tones.mk installs every tone, by its own Vanta_ name" python3 - <<'EOF'
import glob, os, re
mk = open("vendor/vanta/tones/tones.mk").read()
files = sorted(os.path.relpath(f, "vendor/vanta/tones") for f in glob.glob("vendor/vanta/tones/*/*.ogg"))
listed = sorted(re.findall(r"\$\(VANTA_TONES\)/(\S+\.ogg):", mk))
assert files == listed, f"on disk but not installed: {set(files) - set(listed)}; listed but missing: {set(listed) - set(files)}"
bad = [f for f in files if not os.path.basename(f).startswith("Vanta_")]
assert not bad, f"AOSP-named tones lose to AllAudio.mk (first copy wins): {bad}"
assert "wildcard" not in mk, "explicit list only"
EOF
run "UI sound overlays name only files that ship" python3 - <<'EOF'
import os, re
names = set(os.listdir("vendor/vanta/tones/ui"))
xml = open("vendor/vanta/overlay/VantaSoundsOverlay/res/xml/audio_assets.xml").read()
for f in re.findall(r'file="(Vanta_[^"]+)"', xml):
    assert f in names, f
for f in re.findall(r"/ui/(Vanta_[^<]+)<", open("vendor/vanta/overlay/VantaSoundsSettingsOverlay/res/values/defaults.xml").read()):
    assert f in names, f
EOF
run "the device name is not a lab node" bash -c "! grep -q 'lab node' design/tokens.json"

echo "== home and cover"
run "exactly one Vanta app is a home launcher (VantaHome); a second HOME means a chooser" python3 - <<'EOF'
import glob, re
homes = []
for m in glob.glob("vendor/vanta/packages/*/AndroidManifest.xml"):
    for f in re.findall(r"<intent-filter.*?</intent-filter>", open(m).read(), re.S):
        if "category.HOME" in f and "SETUP_WIZARD" not in f:
            homes.append(m.split("/")[3])
assert homes == ["VantaHome"], homes
EOF
run "VantaHome turns into the cover face when the window is cover-sized" bash -c "grep -q 'isCoverSized' vendor/vanta/packages/VantaHome/src/com/failure/vanta/home/HomeActivity.kt && grep -q 'CoverHome(state)' vendor/vanta/packages/VantaHome/src/com/failure/vanta/home/HomeActivity.kt"
run "every cover panel id has a panel, and every panel an id" python3 - <<'EOF'
import re
cfg = open("vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaConfig.kt").read()
ids = re.findall(r'"(\w+)"', re.search(r"COVER_PANEL_IDS = listOf\((.*?)\)", cfg).group(1))
src = open("vendor/vanta/packages/VantaHome/src/com/failure/vanta/home/cover/CoverHome.kt").read()
found = re.findall(r'^\s+"(\w+)" -> \w+Panel\(', src, re.M)
assert sorted(found) == sorted(ids), (ids, found)
EOF
run "every home card id has a card, and every card an id" python3 - <<'EOF'
import re
cfg = open("vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaConfig.kt").read()
ids = re.findall(r'"(\w+)"', re.search(r"HOME_CARD_IDS = listOf\((.*?)\)", cfg).group(1))
src = open("vendor/vanta/packages/VantaHome/src/com/failure/vanta/home/HomeScreen.kt").read()
body = src.split("for (card in state.prefs.cards) when (card) {", 1)[1].split("\nprivate val CELL_H", 1)[0]
found = re.findall(r'^        "(\w+)" ->', body, re.M)
assert sorted(found) == sorted(ids), (ids, found)
EOF
run "the cover page in Hub only shows on a foldable" bash -c "grep -q 'ro.vanta.foldable' vendor/vanta/packages/VantaHub/src/com/failure/vanta/hub/HubActivity.kt && grep -q 'ro.vanta.foldable=\$(VANTA_FOLDABLE)' vendor/vanta/vanta.mk"

echo "== generated from the Lineage tree (brand strings, fonts, recovery)"
F24=tools/fixtures/lineage-24.0
run "brand RROs match the tree's strings in every locale" python3 tools/gen_branding.py --src "$F24" --check
run "no 'Lineage' left in any brand RRO string" bash -c "! grep -rh '<string' vendor/vanta/overlay/VantaBrand*/res | grep -q Lineage"
run "brand RROs cover the en-GB locale (values/ alone loses to values-en-rGB)" test -f vendor/vanta/overlay/VantaBrandPlatformOverlay/res/values-en-rGB/vanta_brand.xml
TB="$W/brand"; mkdir -p "$TB"; cp -r "$F24/." "$TB/"; sed -i 's/LineageOS version</LineageOS release</' "$TB/lineage-sdk/lineage/res/res/values/strings.xml"
neg "brand drift is detected when Lineage rewords a string" python3 tools/gen_branding.py --src "$TB" --check
sed -i 's/name="lineage_version"/name="lineage_version_gone"/' "$TB/lineage-sdk/lineage/res/res/values/strings.xml"
neg "gen_branding FAILS when a branded string disappears" python3 tools/gen_branding.py --src "$TB"
run "fonts_customization = Lineage's file + IBM Plex" python3 tools/gen_fonts.py --src "$F24" --check
run "Lineage's own font families survive in ours" python3 - <<'EOF'
import re
up = set(re.findall(r'name="([^"]+)"', open("tools/fixtures/lineage-24.0/packages/overlays/Lineage/fonts/etc/fonts_customization.xml").read()))
ours = set(re.findall(r'name="([^"]+)"', open("vendor/vanta/fonts/fonts_customization.xml").read()))
assert up <= ours and "ibm-plex-sans" in ours and "ibm-plex-sans-clock" in ours
EOF
run "font overlay names families fonts_customization defines" python3 - <<'EOF'
import re
fams = set(re.findall(r'name="([^"]+)"', open("vendor/vanta/fonts/fonts_customization.xml").read()))
cfg = re.findall(r'>([a-z-]+)</string>', open("vendor/vanta/overlay/FontIBMPlexSansOverlay/res/values/config.xml").read())
assert cfg and all(c in fams for c in cfg if c.startswith("ibm-plex")), cfg
EOF
run "no Vanta module installs fonts_customization.xml (17 Kati collision)" bash -c "! grep -q 'filename: \"fonts_customization.xml\"' vendor/vanta/Android.bp && ! grep -q vanta_fonts_customization vendor/vanta/vanta.mk"
TFA="$W/fonts-applied"; mkdir -p "$TFA"; cp -r "$F24/." "$TFA/"; tools/fonts.sh "$TFA" >/dev/null; tools/fonts.sh "$TFA" >/dev/null
run "gen_fonts still clean on a tree fonts.sh already ran on (twice)" python3 tools/gen_fonts.py --src "$TFA" --check
TFN="$W/fonts"; mkdir -p "$TFN"; cp -r "$F24/." "$TFN/"; sed -i 's|</fonts-modification>||' "$TFN/packages/overlays/Lineage/fonts/etc/fonts_customization.xml"
neg "gen_fonts FAILS when its anchor moves" python3 tools/gen_fonts.py --src "$TFN"
run "recovery art exists at every size the tree uses" python3 tools/gen_recovery.py --src "$F24" --check
TR="$W/rec"; mkdir -p "$TR"; cp -r "$F24/." "$TR/"
python3 -c "import struct,sys;p=sys.argv[1];b=bytearray(open(p,'rb').read());b[16:20]=struct.pack('>I',999);open(p,'wb').write(b)" "$TR/bootable/recovery/res-xxhdpi/images/logo_image.png"
neg "recovery size drift is detected" python3 tools/gen_recovery.py --src "$TR" --check
run "recovery title line is ASCII (the recovery font is a bitmap of ASCII)" bash -c "! LC_ALL=C grep -P '^\+.*[^\x00-\x7F]' patches/bootable/recovery/*.patch"
run "recovery patch still matches the tree's recovery sources" python3 - <<'EOF'
import re
p = open("patches/bootable/recovery/0001-Vanta-recovery-palette-and-title.patch").read()
src = {"recovery.cpp": open("tools/fixtures/lineage-24.0/bootable/recovery/recovery.cpp").read(),
       "recovery_ui/screen_ui.cpp": open("tools/fixtures/lineage-24.0/bootable/recovery/recovery_ui/screen_ui.cpp").read()}
for f, body in re.findall(r"^--- a/(\S+)\n\+\+\+ b/\S+\n(.*?)(?=^diff --git|\Z)", p, re.S | re.M):
    for hunk in re.split(r"^@@.*$", body, flags=re.M)[1:]:
        old = "\n".join(l[1:] for l in hunk.splitlines() if l[:1] in (" ", "-"))
        assert old in src[f], f"{f}: hunk context no longer in the tree"
EOF
if [ -d build/l24/frameworks/base/.git ]; then
  run "every SystemUI patch applies to the lineage-24.0 reference clone" bash -c 'for p in patches/frameworks/base/*.patch; do git -C build/l24/frameworks/base apply --check "$PWD/$p" || exit 1; done'
fi
if [ "${CHECK_NET:-1}" = 1 ]; then
  run "the whole patch series applies, in order, to fresh lineage-24.0 clones (tools/patchcheck.sh)" tools/patchcheck.sh
fi

echo "== design tokens -> overlays"
run "generated files match design/tokens.json" python3 tools/gen_overlays.py --check
cp design/tokens.json "$W/tokens.bak"
python3 -c "import json;p='design/tokens.json';t=json.load(open(p));t['theme']['accent_color']='FF00FF';open(p,'w').write(json.dumps(t,indent=2)+'\n')"
neg "drift is detected when tokens change" python3 tools/gen_overlays.py --check
cp "$W/tokens.bak" design/tokens.json
run "accent matches the phone's proven identity (35E0FF)" grep -q '"system_palette": "35E0FF"' design/tokens.json

echo "== aura engine (Studio)"
run "VantaAuras generated for every tokens aura" python3 - <<'EOF'
import json, re
t = json.load(open("design/tokens.json"))
auras = [k for k in t["auras"] if not k.startswith("_")]
src = open("vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaAuras.kt").read()
ids = set(re.findall(r'Aura\("([a-z]+)"', src))
missing = [a for a in auras if a not in ids]
assert not missing, f"auras missing from VantaAuras.kt: {missing}"
assert "void" in t["auras"], "void aura (the default) must exist"
for a in auras:
    for k in ("edge", "edge_dim", "glow"):
        assert re.fullmatch(r'[0-9A-Fa-f]{6}', t["auras"][a][k]), f"{a}.{k} not a 6-hex colour"
EOF
run "default aura equals void.colors accent" python3 -c "import json;t=json.load(open('design/tokens.json'));a=t['auras']['void'];c=t['void']['colors'];assert a['edge']==c['edge'] and a['glow']==c['glow'] and a['edge_dim']==c['edge_dim']"
run "Studio config keys exist" bash -c "for k in LOOK_AURA LOOK_GLASS LOOK_WALL_DEPTH LOOK_ICON_SHAPE AMBIENT_STYLE; do grep -q \"\\\"look\\|\\\"ambient\" vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaConfig.kt && grep -q \"const val \$k\" vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaConfig.kt || exit 1; done"
run "VantaTheme takes an aura and publishes LocalAura" bash -c "grep -q 'aura: Aura' vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaTheme.kt && grep -q 'LocalAura provides aura' vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/VantaTheme.kt"
run "render defines the new surfaces" bash -c "for s in studio ambient capsule auras; do grep -q \"\$s: {\" design/render/surfaces.js && grep -q \"\\\"\$s\\\"\" design/render/render.py || exit 1; done"

echo "== build the layer with the SDK"
if [ -x "$AAPT2" ] && [ -f "$JAR" ]; then
  for o in VantaFrameworkOverlay VantaSettingsProviderOverlay VantaRailOnly VantaSettingsOverlay VantaLauncher3Overlay \
           VantaBrandPlatformOverlay VantaBrandPartsOverlay FontIBMPlexSansOverlay VantaRolesOverlay VantaSoundsOverlay VantaSoundsSettingsOverlay; do
    d=vendor/vanta/overlay/$o
    run "aapt2 links $o" bash -c "'$AAPT2' compile --dir $d/res -o '$W/$o.zip' && '$AAPT2' link --manifest $d/AndroidManifest.xml -I '$JAR' -o '$W/$o.apk' '$W/$o.zip'"
  done
  S=vendor/vanta/setup
  run "aapt2 links VantaSetup resources" bash -c "'$AAPT2' compile --dir $S/res -o '$W/s.zip' && '$AAPT2' link --manifest $S/AndroidManifest.xml -I '$JAR' -o '$W/s.apk' '$W/s.zip' --java '$W/gen'"
  run "javac compiles VantaSetup + its test" bash -c "mkdir -p '$W/cls' && javac -nowarn -cp tools/lib/json-20240303.jar:'$JAR' -d '$W/cls' '$W'/gen/com/failure/vanta/setup/R.java \$(find $S/src -name '*.java') tools/TestIdentity.java"
  run "theme JSON merge keeps the ROM's keys (TestIdentity)" java -cp "tools/lib/json-20240303.jar:$W/cls:$JAR" com.failure.vanta.setup.TestIdentity
else
  ok 1 "Android SDK (aapt2 + android.jar) available at $SDK"
fi

echo "== post-flash gate (tools/gate.sh vs fake adb)"
export ADB="$P/tools/fake/bin/adb"
run "gate passes on a healthy device" tools/gate.sh
for f in boot vanta a17 slots data applied accent font overlay motion desktop home root; do
  neg "gate catches fault: $f" env FAULT=$f tools/gate.sh
done
run "gate passes on a healthy Flip5" env FAKE_DEVICE=b5q tools/gate.sh
for f in cover home; do
  neg "gate catches Flip5 fault: $f" env FAKE_DEVICE=b5q FAULT=$f tools/gate.sh
done
run "the Flip5 gate does not ask for the S10's dual SIM or KernelSU" bash -c "env FAKE_DEVICE=b5q FAULT=root tools/gate.sh >/dev/null && env FAKE_DEVICE=b5q FAULT=slots tools/gate.sh >/dev/null"
unset ADB

echo "== host preflight"
neg "preflight refuses this box" env VANTA_CORES=8 VANTA_RAM_GB=16 VANTA_DISK_GB=2000 tools/preflight.sh "$W/src"
run "preflight accepts a 64-core / 512 GB box" env VANTA_CORES=64 VANTA_RAM_GB=512 VANTA_DISK_GB=2000 tools/preflight.sh "$W/src"
neg "preflight refuses 64 cores with 32 GB RAM" env VANTA_CORES=64 VANTA_RAM_GB=32 VANTA_DISK_GB=2000 tools/preflight.sh "$W/src"
neg "apply.sh refuses an unsynced tree" tools/apply.sh "$W/not-a-tree"
neg "ksu.sh refuses a missing kernel" kernel/ksu.sh "$W/not-a-tree"

echo "== prebuilts"
run "stage.sh stages the boot animation with the optional APKs off" env VANTA_WITH_BRIDGE=false VANTA_WITH_HALO=false tools/stage.sh
run "with the flags off, prebuilt/Android.bp declares no app (nothing for Soong to miss)" bash -c "! grep -q android_app_import vendor/vanta/prebuilt/Android.bp"
run "staged boot animation is Vanta's own (tools/bootanim)" bash -c "cmp -s vendor/vanta/prebuilt/bootanimation.zip out/bootanim/bootanimation.zip && grep -q 'WORDMARK = \"vanta\"' tools/bootanim/make.py"
run "staged boot animation is STORED with desc.txt" python3 -c "
import zipfile; z=zipfile.ZipFile('vendor/vanta/prebuilt/bootanimation.zip')
assert 'desc.txt' in z.namelist() and all(i.compress_type==0 for i in z.infolist())"
run "prebuilts stay out of git" grep -qx 'prebuilt/' vendor/vanta/.gitignore

echo "== wallpaper shader is one file"
SH=vendor/vanta/packages/VantaAurora/res/raw/liquid_frag.glsl
run "Aurora loads liquid_frag" grep -q 'R.raw.liquid_frag' vendor/vanta/packages/VantaAurora/src/com/failure/vanta/aurora/AuroraWallpaperService.kt
run "browser render loads the ROM's own shader" grep -q "VantaAurora/res/raw/" design/render/wall.js
run "no second copy of the shader anywhere" bash -c "[ \$(find design vendor -name 'liquid_frag.glsl' -not -path '*/build/*' | wc -l) = 1 ]"
run "shader declares every uniform the renderer sets" bash -c "for u in uRes uTime uIntensity uDay uWake uOffset; do grep -q \"uniform .* \$u;\" $SH || exit 1; done"
if command -v glslangValidator >/dev/null; then
  cp "$SH" "$W/liquid.frag"; run "shader compiles as GLSL ES 3.00" glslangValidator "$W/liquid.frag"
  sed 's/fragColor = vec4/fragColor = vec3/' "$SH" > "$W/bad.frag"; neg "a broken shader fails the compile" glslangValidator "$W/bad.frag"
fi

echo "== cover render"
run "render knows the cover profile" grep -q 'flip5-cover' design/render/devices.js

echo "== load-bearing doc lines"
run "PLAN: G2 mobile data is the gate that decides" grep -q 'G2' PLAN.md
run "PLAN: flashing wipes the phone" grep -qi 'wipes' PLAN.md
run "ril/README: the slot finding is a hypothesis until G2" grep -q 'hypothesis with evidence, not a proof' ril/README.md
run "AGENTS: vendor/extra is the hook" grep -q 'vendor/extra' AGENTS.md
run "AGENTS: the base is LineageOS 24.0" grep -q 'lineage-24.0' AGENTS.md

echo "== Kotlin + Compose at AOSP 17's versions (tools/shadow)"
if [ "${CHECK_SHADOW:-1}" = 1 ]; then
  run "every Vanta app compiles (Kotlin 2.2, Compose 1.12, Material3 1.5; no global opt-in)" tools/shadow/build.sh
else
  echo "skip  shadow compile (CHECK_SHADOW=0)"
fi

echo
echo "check: $pass passed, $fail failed"
[ "$fail" = 0 ]
