#!/bin/bash
# Fetch LFS files from Gitea mirror with retry.
#
# Gitea's mirror-sync API is async — the webhook fires on push but the
# actual sync may still be in progress when CI starts. Retry with backoff
# to bridge the gap.
#
# Usage:
#   ./ci/github_actions/fetch_lfs.sh                          # full pull
#   ./ci/github_actions/fetch_lfs.sh --include="path/to/*"    # selective pull

set -euo pipefail

MAX_ATTEMPTS=5
RETRY_DELAY=15

git lfs install

echo "LFS objects before pull:"
git lfs ls-files | wc -l

for i in $(seq 1 $MAX_ATTEMPTS); do
    if git lfs pull "$@"; then
        echo "LFS objects after pull:"
        git lfs ls-files | wc -l
        exit 0
    fi
    if [ "$i" -lt "$MAX_ATTEMPTS" ]; then
        echo "LFS pull attempt $i/$MAX_ATTEMPTS failed, retrying in ${RETRY_DELAY}s..."
        sleep $RETRY_DELAY
    fi
done

echo "LFS pull failed after $MAX_ATTEMPTS attempts"
exit 1
