name: Build and Publish Containers

on:
  push:
    branches:
      - main
    tags:
      - "v*"
    paths:
      - "backend/**"
      - ".gitea/workflows/docker-publish.yml"
  workflow_dispatch:

env:
  REGISTRY: ${{ vars.GITEA_REGISTRY || 'git.hudsonriggs.systems' }}
  REGISTRY_USERNAME: ${{ github.actor }}
  REGISTRY_PASSWORD: ${{ secrets.REGISTRY_TOKEN || secrets.GITHUB_TOKEN }}
  IMAGE_NAMESPACE: ${{ vars.GITEA_IMAGE_NAMESPACE || github.repository_owner }}

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    strategy:
      matrix:
        include:
          - name: backend
            context: .
            dockerfile: backend/Dockerfile
            image: rmtpocketwatcher-backend

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

      - name: Normalize image coordinates
        id: image
        shell: bash
        run: |
          REGISTRY_LOWER="$(echo "${REGISTRY}" | tr '[:upper:]' '[:lower:]')"
          NAMESPACE_LOWER="$(echo "${IMAGE_NAMESPACE}" | tr '[:upper:]' '[:lower:]')"
          IMAGE_REF="${REGISTRY_LOWER}/${NAMESPACE_LOWER}/${{ matrix.image }}"

          echo "registry=${REGISTRY_LOWER}" >> "$GITHUB_OUTPUT"
          echo "namespace=${NAMESPACE_LOWER}" >> "$GITHUB_OUTPUT"
          echo "image_ref=${IMAGE_REF}" >> "$GITHUB_OUTPUT"

      - name: Validate registry settings
        shell: bash
        run: |
          if [ -z "${REGISTRY_PASSWORD}" ]; then
            echo "Missing registry credentials. Set REGISTRY_TOKEN or ensure GITHUB_TOKEN has package write access." >&2
            exit 1
          fi

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

      - name: Login to registry
        uses: docker/login-action@v3
        with:
          registry: ${{ steps.image.outputs.registry }}
          username: ${{ env.REGISTRY_USERNAME }}
          password: ${{ env.REGISTRY_PASSWORD }}

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ steps.image.outputs.image_ref }}
          tags: |
            type=sha
            type=ref,event=branch
            type=ref,event=tag
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: ${{ matrix.context }}
          file: ${{ matrix.dockerfile }}
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ steps.image.outputs.image_ref }}:buildcache
          cache-to: type=registry,ref=${{ steps.image.outputs.image_ref }}:buildcache,mode=max
