# docker-build.yaml

name: Docker Build

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

jobs:
  docker:
    runs-on: ubuntu-latest

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

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

      - name: Extract tag name
        if: startsWith(github.ref, 'refs/tags/')
        run: echo "GIT_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV

      - name: Log in to registry
        if: secrets.REGISTRY != '' && secrets.REGISTRY_USER != '' && secrets.REGISTRY_PASSWORD != ''
        uses: docker/login-action@v3
        with:
          registry: ${{ secrets.REGISTRY }}
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Check if SHA image exists
        if: env.GIT_TAG != '' && secrets.REGISTRY != ''
        id: check_image
        run: |
          if docker manifest inspect ${{ secrets.REGISTRY }}5mdt/vitrify-me:${{ github.sha }} > /dev/null 2>&1; then
            echo "image_exists=true" >> $GITHUB_OUTPUT
          else
            echo "image_exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Pull existing image
        if: env.GIT_TAG != '' && steps.check_image.outputs.image_exists == 'true'
        run: docker pull ${{ secrets.REGISTRY }}5mdt/vitrify-me:${{ github.sha }}

      - name: Build Docker image
        if: env.GIT_TAG == '' || steps.check_image.outputs.image_exists == 'false'
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: ${{ secrets.REGISTRY != '' }}
          tags: ${{ secrets.REGISTRY }}5mdt/vitrify-me:${{ github.sha }}

      - name: Tag and push with git tag
        if: env.GIT_TAG != '' && secrets.REGISTRY != ''
        run: |
          docker tag ${{ secrets.REGISTRY }}5mdt/vitrify-me:${{ github.sha }} ${{ secrets.REGISTRY }}5mdt/vitrify-me:${{ env.GIT_TAG }}
          docker push ${{ secrets.REGISTRY }}5mdt/vitrify-me:${{ env.GIT_TAG }}
