#!/usr/bin/env bash
# Source trees of this repo that don't write crates/metal2vulkan-validation/corpus/observations
# again: 1.5 GiB of the 1.6 GiB tracked tree, read only by validation runs.
#
#   scripts/lean-tree worktree PATH NEW_BRANCH START_REV
#   scripts/lean-tree snapshot REV DEST_DIR [--with-observations]
#
# worktree adds a git worktree on a new branch, with every tracked file. The observations are
# copy-on-write clones of the main worktree's (cp -c on APFS, --reflink=auto elsewhere), which write
# nothing until a file in them changes. git then hashes the clones against START_REV and rewrites
# only the files that differ; files START_REV doesn't track are removed from the clone, so the tree
# is exactly START_REV's whatever the main worktree holds.
# When the main worktree has no observations to clone, git checks them out as usual.
#
# snapshot extracts `git archive REV` into DEST_DIR with `tar -xm`, so every file carries the
# extraction time and a target built before it can't take these sources as Fresh. It leaves the
# observations out unless --with-observations is given.
#
# Both act on the repository this script is in, from any of its worktrees.
set -euo pipefail

die() {
  echo "lean-tree: $*" >&2
  exit 2
}

clone() {
  if [ "$(uname)" = Darwin ]; then
    cp -c -p -R "$1" "$2"
  else
    cp -a --reflink=auto "$1" "$2"
  fi
}

repo=$(git -C "$(dirname "$0")" rev-parse --show-toplevel)
observations=crates/metal2vulkan-validation/corpus/observations

case "${1:-}" in
worktree)
  [ $# -eq 4 ] || die "usage: lean-tree worktree PATH NEW_BRANCH START_REV"
  path=$2
  branch=$3
  start=$4
  main=$(git -C "$repo" worktree list --porcelain | sed -n '1s/^worktree //p')
  # Added from the main worktree: a worktree takes the sparse-checkout settings of the one it is
  # added from.
  if [ ! -d "$main/$observations" ]; then
    git -C "$main" worktree add -b "$branch" "$path" "$start"
    exit 0
  fi
  git -C "$main" worktree add --no-checkout -b "$branch" "$path" "$start"
  mkdir -p "$path/$(dirname "$observations")"
  clone "$main/$observations" "$path/$observations"
  # The index from START_REV with the working tree untouched; hashing the clones records the ones
  # that match, the checkout writes everything else, and clean removes what START_REV doesn't track.
  git -C "$path" reset -q
  git -C "$path" update-index -q --refresh || true
  git -C "$path" checkout -q -- .
  git -C "$path" clean -q -f -d -x -- "$observations"
  ;;
snapshot)
  [ $# -ge 3 ] || die "usage: lean-tree snapshot REV DEST_DIR [--with-observations]"
  rev=$2
  dest=$3
  mkdir -p "$dest"
  if [ "${4:-}" = --with-observations ]; then
    git -C "$repo" archive --format=tar "$rev" | tar -xm -C "$dest"
  else
    git -C "$repo" archive --format=tar "$rev" -- . ":(exclude)$observations" | tar -xm -C "$dest"
  fi
  ;;
*) die "usage: lean-tree worktree|snapshot ..." ;;
esac
