name: Publish Docker Image

on:
  push:
    tags:
      - 'v*.*.*'

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

jobs:
  publish:
    if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref_name, '-')
    runs-on: ubuntu-latest

    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout release tag
        uses: actions/checkout@v4

      - name: Validate stable semver tag
        id: tag
        run: |
          if [[ "${GITHUB_REF_NAME}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "publish=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          echo "publish=false" >> "$GITHUB_OUTPUT"
          echo "Skipping non-stable semver tag ${GITHUB_REF_NAME}"

      - name: Set up QEMU
        if: steps.tag.outputs.publish == 'true'
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        if: steps.tag.outputs.publish == 'true'
        uses: docker/setup-buildx-action@v3

      - name: Derive image metadata
        if: steps.tag.outputs.publish == 'true'
        id: meta
        run: |
          VERSION="${GITHUB_REF_NAME#v}"
          MINOR="${VERSION%.*}"
          MAJOR="${VERSION%%.*}"
          OWNER_LOWER=$(echo "${GITHUB_REPOSITORY_OWNER}" | tr '[:upper:]' '[:lower:]')
          IMAGE="ghcr.io/${OWNER_LOWER}/ccs-dashboard"

          {
            echo "version=${VERSION}"
            echo "minor=${MINOR}"
            echo "major=${MAJOR}"
            echo "image=${IMAGE}"
          } >> "$GITHUB_OUTPUT"

      - name: Log in to GitHub Container Registry
        if: steps.tag.outputs.publish == 'true'
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push release image
        if: steps.tag.outputs.publish == 'true'
        uses: docker/build-push-action@v6
        with:
          context: .
          file: docker/Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
            ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.minor }}
            ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.major }}
            ${{ steps.meta.outputs.image }}:latest
          labels: |
            org.opencontainers.image.title=ccs-dashboard
            org.opencontainers.image.description=CCS Dashboard container image
            org.opencontainers.image.url=https://github.com/${{ github.repository }}
            org.opencontainers.image.source=https://github.com/${{ github.repository }}
            org.opencontainers.image.version=${{ steps.meta.outputs.version }}
            org.opencontainers.image.revision=${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
