#!/usr/bin/env bash
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
origin="$(git remote get-url origin)"
origin="${origin%/}"
remote_root="$(printf '%s\n' "$origin" | sed -E 's#/[^/]+(\.git)?$##')"
remote_root="${remote_root%/*}"
echo "remote_root: $remote_root"
get_default_branch() {
  local repo="$1"
  local branch
  branch="$(git ls-remote --symref "$repo" HEAD | awk '$1 == "ref:" {
    sub("^refs/heads/", "", $2)
    print $2
    exit
  }')"
  if [ -z "$branch" ]; then
    printf '无法获取远程仓库默认分支: %s\n' "$repo" >&2
    return 1
  fi
  printf '%s\n' "$branch"
}
fetch_repo() {
  local repo="$1"
  local dir="$2"
  local branch="${3-}"
  if [ -z "$branch" ]; then
    branch="$(get_default_branch "$repo")"
  fi
  if [ -d "$dir" ]; then
    git -C "$dir" rev-parse --is-inside-work-tree >/dev/null
    git -C "$dir" remote set-url origin "$repo"
    git -C "$dir" fetch origin "$branch"
    git -C "$dir" checkout "$branch"
    git -C "$dir" pull --ff-only origin "$branch"
  else
    git clone --branch "$branch" --single-branch "$repo" "$dir"
  fi
}
fetch_repo_ex() {
  local name="$1"
  local branch="${2-}"
  local repo="${remote_root}/${name}"
  local dir="${name##*/}"
  fetch_repo "$repo" "third_party/${dir}" "$branch"
}
fetch_repo_ex "ae/build_infra"
fetch_repo_ex "psc/Structive"
fetch_repo_ex "psc/Adminive"
