#!/usr/bin/env bash
# Run the post-receive tests for a repository, which means:
#
#   1. Cloning the repo to a scratch directory
#   2. Setting up a virtualenv/dependencies
#   3. Running the test suite through `ts`
#
# TODO: Support running tests on the non-main branch.

set -o errexit
set -o nounset

if (( $# != 1 )); then
  echo "Usage: $0 REPO_NAME" >&2
  exit 1
fi

# Print a command in blue, then run the command
run_command() {
    echo -e "\033[34m-> $@\033[0m"
    bash -c "$@"
}

unset GIT_DIR

# REPO_NAME is the name of the repository to run tests for
REPO_NAME="$1"

# REMOTES_ROOT is the directory where I keep all my remote repos
REMOTES_ROOT="/Volumes/Media (Speedwell)/repos"

# SCRATCH_ROOT is the directory where I have checked-out versions for
# running post-receive tests
SCRATCH_ROOT="$REMOTES_ROOT/.working"

export REPO_DIR="$REMOTES_ROOT/$REPO_NAME"
export SCRATCH_DIR="$SCRATCH_ROOT/$REPO_NAME"

export CI=true

# Clone the Git repo to the directory if it doesn't exist yet, or update
# it if it doesn't.
if [ ! -d "$SCRATCH_DIR/.git" ]; then
  run_command 'git clone "$REPO_DIR" "$SCRATCH_DIR"'
  
  run_command 'cd "$SCRATCH_DIR"'
  echo "$SCRATCH_DIR"
  cd "$SCRATCH_DIR"
else
  run_command 'cd "$SCRATCH_DIR"'
  echo "$SCRATCH_DIR"
  cd "$SCRATCH_DIR"

  run_command 'git pull origin main --rebase'
fi

# If there's a requirements.txt file in the repo, then this is a Python repo.
# Set up a virtualenv.
if [ -f "$SCRATCH_DIR/requirements.txt" ] || [ -f "$SCRATCH_DIR/dev_requirements.txt" ]; then
  run_command 'uv venv --quiet --allow-existing .venv --python 3.14'
  echo "$SCRATCH_DIR/.venv" >> ~/.venv_registry
  run_command 'source .venv/bin/activate'
  source .venv/bin/activate  
  run_pip_sync
fi

echo ""

~/repos/scripts/ci/ts
