#!/usr/bin/env bash
# Strip Co-Authored-By trailer lines from unpushed commits
#
# Usage: ./scripts/strip-coauthor.sh [base-ref]
#   base-ref defaults to origin/main

set -euo pipefail

BASE="${1:-origin/main}"

count=$(git log --grep="Co-Authored-By" --oneline "$BASE..HEAD" | wc -l)
if [ "$count" -eq 0 ]; then
  echo "No commits with Co-Authored-By found in $BASE..HEAD"
  exit 0
fi

echo "Rewriting $count commit(s) to strip Co-Authored-By lines..."

git filter-branch -f --msg-filter '
  sed "/^Co-Authored-By:.*$/d" | sed -e :a -e "/^\n*$/{$d;N;ba;}"
' "$BASE..HEAD"

remaining=$(git log --grep="Co-Authored-By" --oneline "$BASE..HEAD" | wc -l)
if [ "$remaining" -eq 0 ]; then
  echo "Done. All Co-Authored-By lines removed."
else
  echo "WARNING: $remaining commit(s) still contain Co-Authored-By lines."
  exit 1
fi
