name: Release

# Builds the nine platform jars and publishes them as a GitHub release.
#
# Two ways in:
#   - push a tag matching v* (e.g. v1.0.0) -- the release is created at that
#     tag, and the tag is checked against mod_version in gradle.properties so
#     the jars and the release cannot disagree about what version they are;
#   - run it by hand (workflow_dispatch) -- the release is created at the
#     dispatched commit under the tag derived from mod_version, creating the
#     tag if it does not exist yet.
on:
  push:
    tags: ['v*']
  workflow_dispatch:

permissions:
  contents: write

concurrency:
  group: release-${{ github.ref }}
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # Loom checks the Minecraft jar against the Gradle JVM at configuration
      # time, and 26.2's jar requires Java 25 -- so Gradle itself has to run on
      # 25. The JDK 21 toolchain the other buckets and the shared modules
      # compile with is provisioned by Gradle through the foojay resolver in
      # settings.gradle, the same mechanism a local build uses.
      - name: Set up JDK 25
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '25'

      - name: Set up Gradle
        uses: gradle/actions/setup-gradle@v4

      - name: Build all platforms
        run: ./gradlew test buildAllPlatforms

      - name: Resolve version
        id: version
        run: |
          VERSION="$(sed -n 's/^mod_version=//p' gradle.properties)"
          echo "mod_version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "tag=v$VERSION" >> "$GITHUB_OUTPUT"
          if [[ "${{ github.event_name }}" == "push" && "v$VERSION" != "${{ github.ref_name }}" ]]; then
            echo "::error::Tag ${{ github.ref_name }} does not match mod_version=$VERSION in gradle.properties (expected v$VERSION)"
            exit 1
          fi

      - name: Collect jars
        run: |
          mkdir -p dist
          for jar in platform/*/build/libs/*.jar; do
            case "$jar" in
              *-sources.jar) ;;
              *) cp "$jar" dist/ ;;
            esac
          done
          # platform/common is a source root, not a bucket -- count the real ones.
          buckets="$(ls -d platform/*/ | grep -vc 'platform/common/')"
          jars="$(ls dist | wc -l)"
          test "$jars" -eq "$buckets"
          ls -la dist

      - name: Publish release
        uses: softprops/action-gh-release@v2
        with:
          # On a tag push the pushed tag is used as-is; on a manual run the
          # tag comes from mod_version and is created at the built commit.
          tag_name: ${{ github.event_name == 'workflow_dispatch' && steps.version.outputs.tag || '' }}
          target_commitish: ${{ github.event_name == 'workflow_dispatch' && github.sha || '' }}
          files: dist/*
          generate_release_notes: true
          fail_on_unmatched_files: true
