#!/usr/bin/env bash
#
# checkpoint-fold.sh  -  fold a run's checkpoint commits back into the working
# tree before the real commit.
#
# A run commits as it goes so a crash loses nothing: Phase 2 writes
# `wip(<scope>): <summary> [<task>]` after each plan task, and the user test
# writes `WIP: <task>  -  changes for user test`. None of them belongs in the
# PR. This counts those commits from HEAD down, following first parents, and
# stops at the first commit that is neither, so a commit someone else made on
# the branch is never touched. The count is bounded by origin/<base> when that
# ref exists. A mixed reset then leaves the changes unstaged for the caller to
# stage file by file.
#
# Usage:
#   checkpoint-fold.sh --repo <dir> --task <id> [--base <branch>] [--dry-run]
#
# Prints {"folded": N}. Exit codes: 0 done (N may be 0), 1 usage error,
# 6 the fold would pass the first commit of the history, or the reset failed.
set -uo pipefail

usage() {
  echo "usage: checkpoint-fold.sh --repo <dir> --task <id> [--base <branch>] [--dry-run]" >&2
  exit 1
}

REPO="" TASK="" BASE="" DRY=0
while [ $# -gt 0 ]; do
  case "$1" in
    --dry-run) DRY=1; shift; continue ;;
  esac
  [ $# -ge 2 ] || usage
  case "$1" in
    --repo) REPO="$2" ;;
    --task) TASK="$2" ;;
    --base) BASE="$2" ;;
    *) echo "checkpoint-fold: unknown argument $1" >&2; usage ;;
  esac
  shift 2
done
[ -n "$REPO" ] && [ -n "$TASK" ] || usage
git -C "$REPO" rev-parse --git-dir >/dev/null 2>&1 || { echo "checkpoint-fold: --repo is not a git repository" >&2; exit 1; }

RANGE=HEAD
if [ -n "$BASE" ] && git -C "$REPO" rev-parse -q --verify "origin/$BASE" >/dev/null; then
  RANGE="origin/$BASE..HEAD"
fi

N="$(git -C "$REPO" log --first-parent --format=%s "$RANGE" 2>/dev/null | awk -v id="$TASK" '
  $0 == "WIP: " id || index($0, "WIP: " id " ") == 1 || ($0 ~ /^wip\(/ && index($0, "[" id "]")) { n++; next }
  { exit }
  END { print n + 0 }')"

if [ "$N" -gt 0 ] && [ "$DRY" = 0 ]; then
  git -C "$REPO" rev-parse -q --verify "HEAD~$N" >/dev/null ||
    { echo "checkpoint-fold: every commit down to the root is a checkpoint; fold by hand" >&2; exit 6; }
  git -C "$REPO" reset -q "HEAD~$N" || exit 6
fi
printf '{"folded":%s}\n' "$N"
