#!/bin/sh
# Перед push убирает Co-authored-by из исходящих коммитов
remote="$1"
url="$2"

strip_msg() {
  sed '/^Co-authored-by:/Id'
}

while read local_ref local_sha remote_ref remote_sha; do
  if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
    continue
  fi

  if [ "$remote_sha" = "0000000000000000000000000000000000000000" ]; then
    range="$local_sha"
    if ! git log "$local_sha" --format=%B | grep -q "^Co-authored-by:"; then
      continue
    fi
  else
    range="${remote_sha}..${local_sha}"
    if ! git log "$range" --format=%B 2>/dev/null | grep -q "^Co-authored-by:"; then
      continue
    fi
  fi

  echo "Removing Co-authored-by from unpushed commits before push..."
  count=$(git rev-list --count "$range" 2>/dev/null || echo 0)
  if [ "$count" -le 1 ]; then
    msg=$(git log -1 --format=%B "$local_sha" | strip_msg)
    git commit --amend -m "$msg" --no-verify
  else
    git filter-branch -f --msg-filter 'sed "/^Co-authored-by:/Id"' "$range"
  fi
done

exit 0
