name: publish-go-package

on:
  workflow_dispatch:

permissions:
  contents: write

jobs:
  publish:
    runs-on: ubuntu-24.04

    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version-file: go/go.mod
          cache: true
          cache-dependency-path: go/go.sum

      - name: Validate release ref
        id: validate
        shell: bash
        run: |
          set -euo pipefail
          REF_TYPE='${{ github.ref_type }}'
          REF_NAME='${{ github.ref_name }}'
          if [[ "$REF_TYPE" != "branch" ]]; then
            echo "This workflow must be run from a branch. Got ref_type: $REF_TYPE" >&2
            exit 1
          fi
          if [[ ! "$REF_NAME" =~ ^rc-go-[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "This workflow must be run from an rc-go-*.*.* branch. Got: $REF_NAME" >&2
            exit 1
          fi
          RELEASE_VERSION="${REF_NAME#rc-go-}"
          echo "release_version=$RELEASE_VERSION" >> "$GITHUB_OUTPUT"

      - name: Require commit to be on master
        shell: bash
        run: |
          set -euo pipefail
          git fetch origin master
          if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/master; then
            echo "Refusing to release: $GITHUB_SHA is not an ancestor of origin/master" >&2
            exit 1
          fi

      - name: Run tests
        working-directory: go
        run: |
          go test ./...
          go test -tags secp256k1 ./...

      - name: Create and push release tag
        shell: bash
        run: |
          set -euo pipefail
          TAG_NAME="go/v${{ steps.validate.outputs.release_version }}"
          if git ls-remote --exit-code --tags origin "$TAG_NAME" >/dev/null 2>&1; then
            echo "Tag already exists: $TAG_NAME" >&2
            exit 1
          fi
          git tag "$TAG_NAME"
          git push origin "$TAG_NAME"
