name: release

# Push a tag matching vX.Y.Z (e.g. v1.2.3) to build and publish a release.
# The tag drives the version — nothing to bump in source files beforehand.
on:
  push:
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+"

jobs:
  build:
    # Needed to create the release and upload assets with GITEA_TOKEN below,
    # regardless of this instance's default Actions permission mode.
    permissions:
      contents: write
    # Must match a label your act_runner is registered with. The runner's
    # own default label-image is irrelevant here since `container:` below
    # overrides the actual build image per-job.
    runs-on: ubuntu-latest
    container:
      # :latest — always the most recently pushed build-image.sh output.
      # Pin to a specific tag here (see build-image/VERSION) if you need a
      # release build to be reproducible against an exact toolchain image.
      image: cr.ladkau.de/schwert-und-magie/builder:latest
      # Lets the runner pull a private image without a manual `docker login`
      # on the runner host — see docs/publish.md §4.3.
      credentials:
        username: ${{ secrets.REGISTRY_USER }}
        password: ${{ secrets.REGISTRY_PASSWORD }}

    steps:
      - uses: actions/checkout@v4

      - name: Write release signing credentials
        run: |
          set -euo pipefail
          echo "${{ secrets.RELEASE_KEYSTORE_B64 }}" | base64 -d \
            > SchwertUndMagieOnPebbleCompanionApp/release.keystore
          printf '%s\n' "${{ secrets.RELEASE_KEYSTORE_PROPERTIES }}" \
            > SchwertUndMagieOnPebbleCompanionApp/keystore.properties

      - name: Build artifacts
        run: |
          set -euo pipefail
          VERSION="${{ gitea.ref_name }}"
          VERSION="${VERSION#v}"
          VERSION="$VERSION" ./dist.sh

      - name: Create release and upload artifacts
        run: |
          set -euo pipefail
          API="${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}"
          AUTH="Authorization: token ${{ secrets.GITEA_TOKEN }}"

          RELEASE_ID="$(curl -sf -X POST "$API/releases" \
            -H "$AUTH" -H "Content-Type: application/json" \
            -d "{\"tag_name\": \"${{ gitea.ref_name }}\", \"name\": \"${{ gitea.ref_name }}\"}" \
            | jq -r .id)"

          for f in dist/*; do
            curl -sf -X POST "$API/releases/$RELEASE_ID/assets?name=$(basename "$f")" \
              -H "$AUTH" -F "attachment=@$f"
          done
