#!/usr/bin/env bash
# wip-takeover <branch>
# On the receiving machine: fetch refs/wip/snap/<branch>, check the lease names
# this machine, recreate branch + index + worktree exactly, print HANDOFF.md.
set -euo pipefail
die(){ echo "wip-takeover: $*" >&2; exit 1; }
BR="${1:-}"; [ -n "$BR" ] || die "usage: wip-takeover <branch>"
ME="${MACHINE_ID:-$(git config --get wip.machine || true)}"; [ -n "$ME" ] || die "set MACHINE_ID"
REMOTE="${WIP_REMOTE:-origin}"
cd "$(git rev-parse --show-toplevel)"
git fetch -q "$REMOTE" "+refs/wip/snap/$BR:refs/wip-remote/snap/$BR" "+refs/wip/lease/$BR:refs/wip-remote/lease/$BR" \
  || die "no handoff for $BR on $REMOTE"
L="refs/wip-remote/lease/$BR"; W="refs/wip-remote/snap/$BR"
OWNER="$(git log -1 --format=%B "$L" | sed -n 's/^owner=//p')"
[ "$OWNER" = "$ME" ] || die "lease for $BR names $OWNER, not $ME"
[ "$(git log -1 --format=%B "$L" | sed -n 's/^snap=//p')" = "$(git rev-parse "$W")" ] || die "lease and snapshot disagree; ask the sender to re-run wip-handoff"
[ -z "$(git status --porcelain --untracked-files=all)" ] || die "working tree not clean; commit or stash first"
BASE="$(git rev-parse "$W^1")"; ITREE="$(git rev-parse "$W^2^{tree}")"
if git rev-parse -q --verify "refs/heads/$BR" >/dev/null; then
  git merge-base --is-ancestor "refs/heads/$BR" "$BASE" || die "local $BR has commits not in the snapshot; resolve by hand"
fi
git checkout -q -B "$BR" "$BASE"
git read-tree -u --reset "$W"      # worktree := snapshot (adds, edits, deletions)
git read-tree "$ITREE"             # index := what the sender had staged
n=0
git fetch -q "$REMOTE" "+refs/wip/stash/$BR/*:refs/wip-remote/stash/$BR/*" 2>/dev/null || true
for s in $(git for-each-ref --format='%(objectname)' --sort=-refname "refs/wip-remote/stash/$BR/"); do
  git stash store -m "from handoff" "$s"; n=$((n+1)); done
# the branch itself may exist on the remote (pushed before the handoff): track it
if git fetch -q "$REMOTE" "+refs/heads/$BR:refs/remotes/$REMOTE/$BR" 2>/dev/null; then
  git branch -q --set-upstream-to="$REMOTE/$BR" "$BR"
else
  git config "branch.$BR.remote" "$REMOTE"; git config "branch.$BR.merge" "refs/heads/$BR"
fi
git config "wip.branch.$BR.handedoff" ""
echo "took over $BR at base ${BASE:0:10}; restored stashes=$n"
echo "----- .wip/HANDOFF.md -----"; cat .wip/HANDOFF.md
