name: Docker

on:
  push:
    tags: ['shoebox-v*']
  workflow_call:
    inputs:
      tag:
        description: 'Git tag to build (e.g. shoebox-v0.3.4)'
        required: true
        type: string
  workflow_dispatch:

env:
  REGISTRY_GHCR: ghcr.io
  IMAGE_NAME_GHCR: ${{ github.repository }}
  IMAGE_NAME_DOCKERHUB: deeppjoymajumdar/shoebox

jobs:
  docker:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ inputs.tag || github.ref }}

      - 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 Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

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

      - name: Extract version
        id: version
        run: echo "tag=${GITHUB_REF_NAME#shoebox-}" >> "$GITHUB_OUTPUT"

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: |
            ${{ env.IMAGE_NAME_DOCKERHUB }}
            ${{ env.REGISTRY_GHCR }}/${{ env.IMAGE_NAME_GHCR }}
          tags: |
            type=semver,pattern={{version}},value=${{ steps.version.outputs.tag }}
            type=semver,pattern={{major}}.{{minor}},value=${{ steps.version.outputs.tag }}
            type=semver,pattern={{major}},value=${{ steps.version.outputs.tag }}
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
