name: Build

on:
  workflow_call:
    inputs:
      dockerfile:
        required: true
        type: string
      context:
        required: true
        type: string
      image-name:
        required: true
        type: string
      build-args:
        required: false
        type: string

jobs:
  build:
    name: Build Images
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2.2.1
      - name: Login to container registry
        uses: docker/login-action@v2.1.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Get base registry
        run: |
          echo "REGISTRY=ghcr.io/${GITHUB_REPOSITORY,,}" >> $GITHUB_ENV
      - name: Set tag prefix
        if: github.ref_name != 'main'
        run: |
          echo "TAG_PREFIX=${{ github.ref_name }}-" >> $GITHUB_ENV
      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v4.1.1
        with:
          images: ${{ env.REGISTRY }}/${{ inputs.image-name }}
          tags: |
            type=raw,value=latest,enable=${{ github.ref_name == 'main' }}
            type=sha,prefix=${{ env.TAG_PREFIX }},format=short,enable=${{ github.ref_name != 'main' }}
            type=ref,event=tag,enable=${{ github.ref_name != 'main' }}
      - name: Build and push Docker image
        uses: docker/build-push-action@v3.2.0
        with:
          file: ${{ inputs.dockerfile }}
          context: ${{ inputs.context }}
          build-args: ${{ inputs.build-args }}
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
