#!/usr/bin/env bash

# Clone or safely update the shared repository, install its public Codex skills,
# and sync public project defaults into long-term memory. Designed to be run by
# a collaborator's Codex session.

set -euo pipefail

repo_url="${RESEARCH_INSTITUTE_PRO_REPO_URL:-git@codeup.aliyun.com:60069db88deaa14d9e02b875/research-institute-pro/research-institute-pro-skill-hub.git}"
target_dir="${RESEARCH_INSTITUTE_PRO_DIR:-$HOME/code/research-institute-pro-skill-hub}"

if [[ -d "$target_dir/.git" ]]; then
  git -C "$target_dir" fetch origin master
  git -C "$target_dir" pull --ff-only origin master
elif [[ -e "$target_dir" ]]; then
  printf 'ERROR: target exists but is not a Git checkout: %s\n' "$target_dir" >&2
  exit 1
else
  mkdir -p "$(dirname "$target_dir")"
  git clone "$repo_url" "$target_dir"
fi

bash "$target_dir/scripts/install_skills_to_codex.sh"

archive_person="$(git -C "$target_dir" config --get research-institute.archivePerson || true)"
if [[ -z "$archive_person" ]]; then
  archive_person="$(git -C "$target_dir" config --get user.name || true)"
  if [[ -z "$archive_person" ]]; then
    printf 'ERROR: set your own Git user.name before enabling daily Q&A archive.\n' >&2
    exit 1
  fi
  git -C "$target_dir" config --local research-institute.archivePerson "$archive_person"
fi

printf 'BOOTSTRAP_OK repository=%s archive_person=%s\n' "$target_dir" "$archive_person"
