name: Build and Publish Mana Loop Docker Image

on:
  push:
    branches:
      - master
      - main
  workflow_dispatch:
    inputs:
      image_tag:
        description: "Custom image tag (optional)"
        required: false
        default: ""

jobs:
  build-and-publish:
    runs-on: ubuntu-latest
    env:
      IMAGE_HOST: gitea.tailf367e3.ts.net
      IMAGE_OWNER: anexim
      IMAGE_NAME: mana-loop

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

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

      - name: Login to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.IMAGE_HOST }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Extract metadata for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE_HOST }}/${{ env.IMAGE_OWNER }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=sha,prefix=
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: |
            ${{ env.IMAGE_HOST }}/${{ env.IMAGE_OWNER }}/${{ env.IMAGE_NAME }}:latest
            ${{ github.event.inputs.image_tag != '' && format('{0}/{1}/{2}:{3}', env.IMAGE_HOST, env.IMAGE_OWNER, env.IMAGE_NAME, github.event.inputs.image_tag) || '' }}
            ${{ env.IMAGE_HOST }}/${{ env.IMAGE_OWNER }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
          platforms: linux/amd64
          file: Dockerfile
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Image digest
        run: |
          echo "Successfully pushed image tags:"
          echo "  - ${{ env.IMAGE_HOST }}/${{ env.IMAGE_OWNER }}/${{ env.IMAGE_NAME }}:latest"
          echo "  - ${{ env.IMAGE_HOST }}/${{ env.IMAGE_OWNER }}/${{ env.IMAGE_NAME }}:${{ github.sha }}"
          if [ -n "${{ github.event.inputs.image_tag }}" ]; then
            echo "  - ${{ env.IMAGE_HOST }}/${{ env.IMAGE_OWNER }}/${{ env.IMAGE_NAME }}:${{ github.event.inputs.image_tag }}"
          fi
