name: Docker Image

on:
  workflow_dispatch:
  push:
    branches:
      - "dev"
    tags:
      - "v*"
  pull_request:
    branches:
      - "dev"

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

jobs:
  build:
    runs-on: ubuntu-latest
    if: github.actor != 'dependabot[bot]'
    permissions:
      contents: read
      packages: write
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0 # This ensures all tags are fetched for git describe

      - name: Get version from git
        id: get-version
        run: |
          VERSION=$(git describe --tags 2>/dev/null || echo "dev")
          echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
          echo "Using version: $VERSION"

      - name: Setup Docker buildx
        uses: docker/setup-buildx-action@v3

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

      - name: Extract Docker metadata tags
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}

      # Determine if we should push the image
      - name: Set push flag
        id: push-flag
        run: |
          if [[ "${{ github.event_name }}" != "pull_request" || "${{ github.event.pull_request.head.repo.full_name }}" == "${{ github.repository }}" ]]; then
            echo "PUSH=true" >> $GITHUB_OUTPUT
          else
            echo "PUSH=false" >> $GITHUB_OUTPUT
          fi

      # Only log in if we're going to push
      - name: Log into registry ${{ env.REGISTRY }}
        if: steps.push-flag.outputs.PUSH == 'true'
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        id: build-and-push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: ${{ steps.push-flag.outputs.PUSH }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: false
          platforms: linux/amd64,linux/arm64
          build-args: |
            VERSION=${{ steps.get-version.outputs.VERSION }}
