#!/bin/bash
# main-at.sh: prints the commit a GitHub branch really pointed to at a given
# moment, read from GitHub's own push log (the repository's Activity view),
# not from commit dates. Reads only.
#
#   bash main-at.sh "2026-10-03 18:00"          # main, in your time zone
#   bash main-at.sh "2026-10-03 18:00" release  # another branch
#   git checkout "$(bash main-at.sh '2026-10-03 18:00')"
#
# Run it inside a clone of the repository. Needs the GitHub CLI (gh), signed in.
# From useyappr.com/blog/git-checkout-by-date
set -euo pipefail

when=${1:?Usage: bash main-at.sh "<date and time>" [branch]}
branch=${2:-main}
repo=$(gh repo view --json nameWithOwner -q .nameWithOwner)

# git reads the date the way --before does, in your time zone. It reads a word
# it doesn't know as "now", so that is refused unless you asked for now.
t=$(git rev-parse --since="$when"); t=${t#--max-age=}
now=$(git rev-parse --since=now); now=${now#--max-age=}
if [ "$t" -ge "$now" ] && [ "$when" != now ]; then
  echo "\"$when\" is in the future, or git couldn't read it as a date. Try \"2026-10-03 18:00\"." >&2; exit 1
fi

last=$(gh api --paginate "repos/$repo/activity?ref=refs/heads/$branch&per_page=100" \
  --jq ".[] | select((.timestamp | fromdateiso8601) <= $t) | [.timestamp, .activity_type, .after] | @tsv" \
  | sort | tail -n 1)

if [ -z "$last" ]; then
  echo "GitHub's log has no push to $branch at or before that time." >&2; exit 1
fi
read -r stamp kind sha <<<"$last"
if [ "$kind" = branch_deletion ]; then
  echo "$branch had been deleted by then ($stamp)." >&2; exit 1
fi
echo "$repo $branch as of $(date -r "$t" '+%Y-%m-%d %H:%M %Z' 2>/dev/null || date -d "@$t" '+%Y-%m-%d %H:%M %Z'): set by a $kind at $stamp" >&2
echo "$sha"
