#!/bin/sh
# Pre-push hook: require annotated tags to be pushed alongside main.
# setuptools-scm derives the release version from git tags — if a tag
# exists on HEAD but isn't included in the push, CI will produce a
# dev version (e.g. 0.1.3.dev2) instead of the intended release.

input=$(cat) || exit 0

pushed_refs=""
has_main=0
main_sha=""

while IFS=' ' read -r local_ref local_sha remote_ref remote_sha; do
    pushed_refs="$pushed_refs $local_ref"
    if [ "$remote_ref" = "refs/heads/main" ]; then
        has_main=1
        main_sha="$local_sha"
    fi
done <<EOF
$input
EOF

[ "$has_main" -eq 0 ] && exit 0

tags=$(git tag --points-at "$main_sha" 2>/dev/null)
[ -z "$tags" ] && exit 0

missing=0
for tag in $tags; do
    tag_ref="refs/tags/$tag"
    case " $pushed_refs " in
        *" $tag_ref "*) ;;
        *)
            echo "ERROR: Commit at main is tagged '$tag' but the tag ref is not in the push."
            echo "  setuptools-scm needs the tag in CI to produce the correct version."
            echo "  Push the tag explicitly: git push origin $tag"
            missing=1
            ;;
    esac
done

[ "$missing" -eq 0 ] && exit 0
exit 1
