#!/usr/bin/env bash
#
# bootstrap: clone the two forks into this workspace.
#
# This repo intentionally tracks only the workspace-level tooling (AGENTS.md and
# scripts/); the frontend and backend forks stay in their own repositories so we
# keep clean upstream histories and can rebase onto new releases. Run this after
# cloning the workspace to lay out:
#
#   gpustack-all-lofyer/
#   ├── gpustack-ui-lofyer/   frontend fork
#   └── gpustack-lofyer/      backend fork
#
# Usage:
#   scripts/bootstrap                 # clone both, checkout the default version
#   scripts/bootstrap v2.2.3          # checkout a specific v<version>-lofyer
#
# Existing clones are left alone (only their remotes are verified).
#
set -o errexit
set -o nounset
set -o pipefail

source "$(dirname "${BASH_SOURCE[0]}")/lib/common.sh"

# Keep in sync with the version table in AGENTS.md.
DEFAULT_VERSION="v2.2.3"
VERSION="${1:-${DEFAULT_VERSION}}"
BRANCH="${VERSION}-lofyer"

require_cmd git

clone_fork() {
  local name="${1}" dir="${2}" origin="${3}" upstream="${4}"

  step "${name}"
  if [[ -d "${dir}/.git" ]]; then
    log "already present at ${dir}"
  else
    log "cloning ${origin}"
    git clone "${origin}" "${dir}"
  fi

  if git -C "${dir}" remote get-url upstream >/dev/null 2>&1; then
    git -C "${dir}" remote set-url upstream "${upstream}"
  else
    git -C "${dir}" remote add upstream "${upstream}"
  fi
  log "origin  : $(git -C "${dir}" remote get-url origin)"
  log "upstream: $(git -C "${dir}" remote get-url upstream)"

  local current
  current="$(repo_branch "${dir}")"
  if [[ "${current}" == "${BRANCH}" ]]; then
    log "already on ${BRANCH}"
  elif git -C "${dir}" rev-parse -q --verify "refs/heads/${BRANCH}" >/dev/null; then
    git -C "${dir}" checkout "${BRANCH}"
  elif git -C "${dir}" rev-parse -q --verify "refs/remotes/origin/${BRANCH}" >/dev/null; then
    git -C "${dir}" checkout -b "${BRANCH}" "origin/${BRANCH}"
  else
    warn "branch ${BRANCH} not found (staying on ${current}); fetch or pick another version"
  fi
}

clone_fork "Frontend" "${UI_REPO}" "${UI_ORIGIN_URL}" "${UI_UPSTREAM_URL}"
clone_fork "Backend"  "${BACKEND_REPO}" "${BACKEND_ORIGIN_URL}" "${BACKEND_UPSTREAM_URL}"

step "Done"
log "frontend: $(repo_branch "${UI_REPO}")"
log "backend : $(repo_branch "${BACKEND_REPO}")"
cat <<EOF

Next steps:
  cd ${UI_REPO} && pnpm install    # or npm install, per the frontend repo
  scripts/build-image              # build + verify the container image
EOF
