#!/usr/bin/env bash
# Lay Vanta over a synced tree. Safe to re-run after every sync: every step is
# idempotent and vendor/vanta is mirrored with --delete.
# Usage: tools/apply.sh [source-root]. Device: VANTA_DEVICE (devices/*.env).
set -euo pipefail
P=$(cd "$(dirname "$0")/.." && pwd)
# shellcheck source=tools/lib/profile.sh
. "$P/tools/lib/profile.sh"; vanta_profile "$P"
SRC=${1:-$HOME/vanta}
[ -f "$SRC/build/envsetup.sh" ] || { echo "apply: $SRC is not a synced tree" >&2; exit 2; }
[ -s "$P/vendor/vanta/prebuilt/bootanimation.zip" ] || "$P/tools/stage.sh"
python3 "$P/tools/gen_overlays.py" --check
# Generated from the Lineage tree itself: fail before building if it moved.
python3 "$P/tools/gen_branding.py" --src "$SRC" --check
python3 "$P/tools/gen_fonts.py" --src "$SRC" --check
python3 "$P/tools/gen_recovery.py" --src "$SRC" --check
if [ "$VANTA_UPREV" != none ]; then python3 "$P/$VANTA_UPREV" --tree "$SRC"; fi
if [ "$VANTA_KSU" = true ]; then "$P/kernel/ksu.sh" "$SRC"; fi
python3 "$P/tools/vendor_fix.py" --tree "$SRC"


mkdir -p "$SRC/vendor/vanta" "$SRC/vendor/extra"
rsync -a --delete "$P/vendor/vanta/" "$SRC/vendor/vanta/"
rsync -a --delete "$P/vendor/extra/" "$SRC/vendor/extra/"
"$P/tools/patches.sh" "$SRC"
"$P/tools/recovery.sh" "$SRC"
"$P/tools/fonts.sh" "$SRC"
python3 "$P/tools/verify_tree.py" "$SRC" --device "$VANTA_DEVICE"
echo "apply: ok ($VANTA_DEVICE)"
