#!/usr/bin/env bash
# repo init LineageOS 24.0 (real android-17.0.0_r1) + the device's local manifest, then sync.
# Usage: tools/sync.sh [source-root]   (default ~/vanta). 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}
mkdir -p "$SRC"; cd "$SRC"
MANIFEST=https://github.com/LineageOS/android
BRANCH=lineage-24.0
# repo init is idempotent, so it always runs: a tree synced from another base
# is re-pointed rather than wiped.
repo init --no-repo-verify --git-lfs --depth=1 -u "$MANIFEST" -b "$BRANCH" \
  -g default,-mips,-darwin,-notdefault
# apply.sh edits these projects in place; put them back so the sync can move
# them (repo refuses to check out over local changes).
for r in $(cd "$P/patches" && find . -name '*.patch' -exec dirname {} \; | sed 's|^\./||' | sort -u) \
         bootable/recovery packages/overlays/Lineage ${VANTA_DEVICE_TREE:-} ${VANTA_KERNEL_TREE:-}; do
  [ -d "$r/.git" ] || [ -f "$r/.git" ] || continue
  git -C "$r" checkout -q -- . && git -C "$r" clean -fdq
done
rm -rf .vanta-applied
mkdir -p .repo/local_manifests
rm -f .repo/local_manifests/*.xml
if [ -n "${VANTA_MANIFEST:-}" ]; then
  install -m 0644 "$P/manifest/$VANTA_MANIFEST" .repo/local_manifests/vanta.xml
fi
# GitHub answers a 64-way fetch with HTTP 429, so the first pass is capped and
# later passes back off; repo only refetches what is still missing.
for jobs in 16 8 4 2; do
  if repo sync -c --no-clone-bundle --no-tags --optimized-fetch --prune \
       --force-sync --force-remove-dirty --retry-fetches=5 -j"$jobs"; then
    echo "sync: ok ($VANTA_DEVICE, $SRC)"; exit 0
  fi
  echo "sync: pass at -j$jobs incomplete, backing off"; sleep 60
done
echo "sync: FAILED after all passes" >&2; exit 1
