#!/usr/bin/env bash
set -euo pipefail

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
VENDOR="$ROOT/vendor"

OPENQ4_URL=https://github.com/themuffinator/OpenQ4.git
OPENQ4_REV=975e296b80b66f63b817d16ea78b53e0685c5c55
GAMELIBS_URL=https://github.com/themuffinator/OpenQ4-game.git
GAMELIBS_REV=eb26e5f3a52358c58ee00bee5602575e5b057164
D3WASM_URL=https://github.com/gabrielcuvillier/d3wasm.git
D3WASM_REV=48f8f65d1216db3ee0b11872bb3b413febadc669
IDTECH4A_URL=https://github.com/glKarin/com.n0n3m4.diii4a.git
IDTECH4A_REV=c414ba2180df5fa7a1d39b8a37765b00212efc7c

sync_repo() {
  local name=$1 url=$2 rev=$3 dest="$VENDOR/$1"
  if [[ ! -d "$dest/.git" ]]; then
    git clone --filter=blob:none "$url" "$dest"
  fi
  git -C "$dest" fetch --depth 1 origin "$rev"
  git -C "$dest" checkout --detach "$rev"
  test "$(git -C "$dest" rev-parse HEAD)" = "$rev"
}

mkdir -p "$VENDOR"
sync_repo openq4 "$OPENQ4_URL" "$OPENQ4_REV"
sync_repo openq4-game "$GAMELIBS_URL" "$GAMELIBS_REV"
sync_repo d3wasm "$D3WASM_URL" "$D3WASM_REV"
sync_repo idtech4a "$IDTECH4A_URL" "$IDTECH4A_REV"

printf 'Pinned OpenQ4 sources are ready in %s\n' "$VENDOR"
