name: release

on:
  push:
    tags: ['v*']

permissions:
  contents: read
  packages: write

jobs:
  docker:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract version from tag
        id: meta
        run: |
          tag="${GITHUB_REF_NAME}"        # e.g. v0.3.0 or v0.3.0-beta.1
          version="${tag#v}"              # strip leading v
          echo "version=$version" >> "$GITHUB_OUTPUT"
          # Emit the full tag list here so the build step never receives a
          # blank tag line (the previous inline `… || ''` conditional left an
          # empty entry for pre-release tags). :latest is added only for
          # stable releases (no pre-release suffix).
          {
            echo "tags<<TAGS_EOF"
            echo "ghcr.io/${GITHUB_REPOSITORY}:${version}"
            if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
              echo "ghcr.io/${GITHUB_REPOSITORY}:latest"
            fi
            echo "TAGS_EOF"
          } >> "$GITHUB_OUTPUT"

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
