#!/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

COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"

MAX_ATTEMPTS=5
RETRY_DELAY=15

if [ -n "${GITHUB_PATH:-}" ]; then
    for path in /opt/homebrew/bin /usr/local/bin; do
        if [ -d "$path" ]; then
            echo "$path" >> "$GITHUB_PATH"
        fi
    done
fi

if ! git lfs version >/dev/null 2>&1; then
    if ! command -v brew >/dev/null 2>&1; then
        echo "ERROR: git-lfs is unavailable, and Homebrew is not on PATH"
        exit 1
    fi

    echo "Installing git-lfs with Homebrew"
    brew install git-lfs
fi

echo "Using git-lfs at $(command -v git-lfs)"
git lfs version

git lfs install --local --force

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

GIT_LFS_PULL=(git lfs pull)
FALLBACK_GITHUB_LFS_PULL=()
if [ -n "${GITHUB_TOKEN:-}" ]; then
    BASIC_AUTH=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 | tr -d '\n')
    GIT_LFS_PULL=(git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $BASIC_AUTH" lfs pull)
    FALLBACK_GITHUB_LFS_PULL=(
        git
        -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $BASIC_AUTH"
        -c "lfs.url=https://github.com/nolen777/eagle0.git/info/lfs"
        lfs
        pull
    )
fi

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

if [ "${#FALLBACK_GITHUB_LFS_PULL[@]}" -gt 0 ]; then
    echo "LFS mirror pull failed after $MAX_ATTEMPTS attempts; trying GitHub LFS fallback"
    if "${FALLBACK_GITHUB_LFS_PULL[@]}" "$@"; then
        echo "LFS objects after GitHub fallback pull:"
        git lfs ls-files | wc -l
        exit 0
    fi
fi

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