#!/bin/sh
set -eu

dst="$1"
repo="$2"
min="${3:-1}"

target="/opt/kb/$dst"

for url in \
  "https://github.com/${repo}.git" \
  "https://gh.xmly.dev/https://github.com/${repo}.git" \
  "https://gh-proxy.com/https://github.com/${repo}.git"
do
  for attempt in 1 2 3
  do
    echo "==> clone $repo"
    echo "    url: $url"
    echo "    attempt: $attempt/3"

    rm -rf "$target"

    if git clone --depth 1 "$url" "$target"; then
      count="$(find "$target" -type f 2>/dev/null | wc -l)"

      if [ "$count" -gt "$min" ]; then
        echo "==> $repo OK ($count files)"
        exit 0
      fi

      echo "==> clone incomplete: only $count files"
    fi

    sleep 5
  done
done

echo "ERROR: failed to clone $repo"
exit 1
