#!/usr/bin/env bash
# wip-prune [<branch>...]: delete refs/wip/{snap,lease,stash}/<branch> on the remote.
# With no args: prune every branch whose refs/heads/<branch> no longer exists on the remote
# (i.e. merged and deleted). Run on machine 7 after merges.
set -euo pipefail
REMOTE="${WIP_REMOTE:-origin}"
ALL="$(git ls-remote "$REMOTE" 'refs/wip/*' | cut -f2)"
if [ $# -gt 0 ]; then BRS="$*"; else
  HEADS="$(git ls-remote --heads "$REMOTE" | cut -f2 | sed 's#^refs/heads/##')"
  BRS="$(echo "$ALL" | sed -n 's#^refs/wip/lease/##p' | while read -r b; do grep -qxF "$b" <<< "$HEADS" || echo "$b"; done)"
fi
DEL=()
for b in $BRS; do
  while read -r r; do [ -n "$r" ] && DEL+=(":$r"); done < <(echo "$ALL" | grep -E "^refs/wip/(snap|lease)/$b\$|^refs/wip/stash/$b/" || true)
done
[ ${#DEL[@]} -gt 0 ] || { echo "wip-prune: nothing to prune"; exit 0; }
git push -q "$REMOTE" "${DEL[@]}"
echo "wip-prune: deleted ${#DEL[@]} refs: ${DEL[*]#:}"
