#!/usr/bin/env bash
#
# Fetch the SDL3 + SDL3_image Android .aar artifacts into app/libs/.
#
# These are not committed (see .gitignore) -- run this once after cloning, and
# again whenever you want to move to a newer SDL.  By default it grabs the
# latest stable release of each; pin a version by passing it, e.g.:
#
#   ./fetch-sdl-aars.sh                 # latest SDL + SDL_image
#   ./fetch-sdl-aars.sh 3.4.10 3.4.4    # pinned SDL / SDL_image versions
#
# build.gradle consumes whatever *.aar lands in app/libs (version-agnostic), so
# no Gradle edit is needed after bumping.

set -euo pipefail
cd "$(dirname "$0")"
LIBS="app/libs"
mkdir -p "$LIBS"

latest_version() {   # repo -> X.Y.Z of the latest "release-*" tag
    curl -fsSL "https://api.github.com/repos/libsdl-org/$1/releases/latest" \
        | sed -n 's/.*"tag_name": *"release-\([0-9.]*\)".*/\1/p' | head -1
}

fetch() {            # repo  aar-basename  [version]
    local repo="$1" name="$2" ver="${3:-}"
    [ -n "$ver" ] || ver="$(latest_version "$repo")"
    [ -n "$ver" ] || { echo "ERROR: could not resolve latest $repo version" >&2; exit 1; }

    local url="https://github.com/libsdl-org/$repo/releases/download/release-${ver}/${name}-devel-${ver}-android.zip"
    echo ">> $name $ver"
    echo "   $url"

    local tmp; tmp="$(mktemp -d)"
    curl -fsSL -o "$tmp/android.zip" "$url"
    rm -f "$LIBS/${name}"-*.aar          # drop any previous version
    unzip -j -o -q "$tmp/android.zip" "*.aar" -d "$LIBS"
    rm -rf "$tmp"
    ls "$LIBS/${name}"-*.aar
}

fetch "SDL"       "SDL3"        "${1:-}"
fetch "SDL_image" "SDL3_image"  "${2:-}"

echo
echo "app/libs now contains:"
ls -1 "$LIBS"/*.aar
