#!/usr/bin/env bash
set -euo pipefail

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

if ! command -v docker >/dev/null 2>&1; then
  echo "rin local ci: docker is not installed, so local containerized commit checks cannot run." >&2
  exit 1
fi

format_targets="$({
  git diff --cached --name-only --diff-filter=ACMR
} | grep -E '^(src|tests|scripts|extensions|docs)/.*\.(ts|js|mjs|md|json|yml|yaml)$|^\.github/workflows/.*\.(yml|yaml)$|^(README\.md|package(-lock)?\.json|tsconfig.*\.json|eslint\.config\.mjs)$' || true)"

image_tag="rin-local-ci:latest"

echo "rin local ci: building container image..."
docker build -f .ci/local-ci/Dockerfile -t "$image_tag" .

tree_id="$(git write-tree)"

echo "rin local ci: running format, lint, test in container..."
archive_file="$(mktemp)"
trap 'rm -f "$archive_file"' EXIT
git archive --format=tar "$tree_id" >"$archive_file"
docker run --rm --network none --memory 4g --memory-swap 4g -e FORMAT_TARGETS_SET=1 -e FORMAT_TARGETS="$format_targets" -i "$image_tag" <"$archive_file"
