name: Release Docker Image
run-name: ${{ github.event.release.tag_name || github.event.inputs.tag || 'manual' }}

on:
  release:
    types: [ published ]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Version tag'
        required: true
        default: '1.0.0'

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: tiny-craft/tiny-rdm

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata (tags, labels)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=semver,pattern={{version}},enable=${{ github.event_name == 'release' }}
            type=raw,value=${{ github.event.inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' }}
            type=raw,value=latest

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Determine version
        id: version
        run: |
          if [ "${{ github.event_name }}" = "release" ]; then
            echo "value=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
          else
            echo "value=${{ github.event.inputs.tag }}" >> "$GITHUB_OUTPUT"
          fi

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          platforms: linux/amd64,linux/arm64
          provenance: false
          sbom: false
          build-args: |
            APP_VERSION=${{ steps.version.outputs.value }}
