name: ci

on:
  push:
    branches:
      - main
      - staging
      - dev
  tags:
    - '*'

jobs:
  docker:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include:
          - service: frontend
            context: frontend
            dockerfile: frontend/Dockerfile
          - service: backend
            context: backend
            dockerfile: backend/Dockerfile

    steps:
      - name: Checkout with submodules
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Derive repository metadata
        id: repo_meta
        run: |
          repo="${GITHUB_REPOSITORY:-$GITEA_REPOSITORY}"
          owner="${repo%%/*}"
          name="${repo##*/}"
          echo "repo_owner=$owner" >> "$GITHUB_OUTPUT"
          echo "repo_name=$name" >> "$GITHUB_OUTPUT"

      - name: Compute base tag
        id: compute_tag
        run: |
          sha="${GITHUB_SHA:-$GITEA_SHA}"
          ref_type="${GITHUB_REF_TYPE:-$GITEA_REF_TYPE}"
          ref_name="${GITHUB_REF_NAME:-$GITEA_REF_NAME}"

          if [ -z "$sha" ]; then
            echo "base_tag=$ref_name" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          short="${sha:0:7}"
          tag="$short"

          if [ "$ref_type" = "tag" ]; then
            tag="$ref_name"
          elif [ "$ref_name" = "dev" ]; then
            tag="${tag}-dev"
          fi

          echo "base_tag=$tag" >> "$GITHUB_OUTPUT"

      - name: Login to local registry
        uses: docker/login-action@v2
        with:
          registry: ${{ vars.REGISTRY_URL }}
          username: ${{ vars.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Login to GHCR
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ vars.GHCR_USERNAME }}
          password: ${{ secrets.GHCR_PASSWORD }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        with:
          driver: remote
          endpoint: ${{ env.BUILDKIT_ARM64_ENDPOINT }}

      - name: Build and Push ${{ matrix.service }} Image
        uses: docker/build-push-action@v6
        with:
          context: ${{ matrix.context }}
          file: ${{ matrix.dockerfile }}
          platforms: linux/arm64
          push: true
          provenance: false
          tags: |
            ${{ vars.REGISTRY_URL }}/${{ steps.repo_meta.outputs.repo_name }}-${{ matrix.service }}:${{ steps.compute_tag.outputs.base_tag }}
            ${{ vars.REGISTRY_URL }}/${{ steps.repo_meta.outputs.repo_name }}-${{ matrix.service }}:${{ gitea.sha }}
            ghcr.io/paperless-dms/${{ steps.repo_meta.outputs.repo_name }}-${{ matrix.service }}:${{ steps.compute_tag.outputs.base_tag }}
            ghcr.io/paperless-dms/${{ steps.repo_meta.outputs.repo_name }}-${{ matrix.service }}:${{ gitea.sha }}
