name: Publish Docker Image

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

concurrency:
  group: docker-${{ github.event.workflow_run.head_sha }}
  cancel-in-progress: true

permissions:
  contents: read
  packages: write

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  docker:
    if: >-
      github.event.workflow_run.conclusion == 'success' &&
      github.event.workflow_run.head_repository.full_name == github.repository
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
        with:
          ref: ${{ github.event.workflow_run.head_sha }}
          fetch-depth: 0

      - name: Resolve release tag
        id: tag
        run: |
          TAG=$(git tag --points-at HEAD | grep '^v' | head -1)
          if [ -z "$TAG" ]; then
            echo "No v* tag at HEAD — skipping publish"
            echo "skip=true" >> "$GITHUB_OUTPUT"
          else
            echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
            echo "skip=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Log in to GHCR
        if: steps.tag.outputs.skip == 'false'
        uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Compute Docker tags
        if: steps.tag.outputs.skip == 'false'
        id: tags
        env:
          REF: ${{ steps.tag.outputs.tag }}
        run: |
          VERSION="${REF#v}"
          FULL="${REGISTRY}/${IMAGE_NAME}"
          FULL="${FULL,,}"

          if echo "$VERSION" | grep -qE '(a|b|rc)[0-9]+$'; then
            TAGS="${FULL}:${VERSION},${FULL}:experimental"
          else
            MINOR="${VERSION%.*}"
            TAGS="${FULL}:${VERSION},${FULL}:${MINOR},${FULL}:stable,${FULL}:latest"
          fi
          echo "tags=${TAGS}" >> "$GITHUB_OUTPUT"

      - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4
        if: steps.tag.outputs.skip == 'false'

      - name: Build and push
        if: steps.tag.outputs.skip == 'false'
        uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7
        with:
          context: .
          push: true
          tags: ${{ steps.tags.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
