name: Build & Publish Docker Image(s)

on:
  push:
    tags:
      - "v*" # trigger on version tags like v1.0.0

permissions:
  contents: read
  packages: write
  id-token: write

jobs:
  get-latest-tag:
    name: Get Latest Git Tag
    runs-on: ubuntu-latest
    outputs:
      tag: ${{ steps.get_tag.outputs.tag }}
    steps:
      - name: Checkout
        uses: actions/checkout@v5
        with:
          fetch-depth: 0 # ensure all tags are fetched

      - name: Get latest Git tag
        id: get_tag
        run: |
          TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "latest")
          echo "tag=$TAG" >> $GITHUB_OUTPUT
          echo "Using tag: $TAG"

  build-and-push:
    needs: get-latest-tag
    runs-on: ubuntu-latest

    steps:
      - name: Checkout source
        uses: actions/checkout@v5

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

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

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

      - name: Build and push image
        uses: docker/build-push-action@v4
        with:
          context: .
          file: ./Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ghcr.io/imgforger/imgforge:latest
            ghcr.io/imgforger/imgforge:${{ needs.get-latest-tag.outputs.tag }}
