name: Build Backend And Update GitOps

on:
  push:
    branches:
      - main
      - high-performance

jobs:
  build-and-update:
    runs-on: ubuntu-latest
    env:
      DOCKER_HOST: unix:///var/run/docker.sock
      GITOPS_USERNAME: ${{ secrets.GITOPS_GITHUB_USERNAME || 'Traceworks2023' }}
      GITOPS_PASSWORD: ${{ secrets.GITOPS_GITHUB_TOKEN || secrets.GITOPS_PAT }}
      GITOPS_REPO: https://github.com/Traceworks2023/nxtgauge-gitops.git
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Docker CLI
        run: |
          apt-get update
          apt-get install -y docker.io git python3

      - name: Log in to registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ci.nxtgauge.com -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin

      - name: Build, push, and update GitOps
        run: |
          set -euo pipefail
          test -n "${GITOPS_PASSWORD:-}" || { echo "GITOPS_PASSWORD is empty"; exit 1; }
          AUTH="$(printf '%s' "${GITOPS_USERNAME}:${GITOPS_PASSWORD}" | base64 -w0)"
          TMP_DIR="$(mktemp -d)"
          git -c http.extraHeader="AUTHORIZATION: basic ${AUTH}" clone --branch main "${GITOPS_REPO}" "${TMP_DIR}"
          while IFS='|' read -r service app_dir; do
            [ -n "${service}" ] || continue
            IMAGE="ci.nxtgauge.com/ashwin/nxtgauge-rust-${service}:${{ github.sha }}"
            docker build -f "${app_dir}/Dockerfile" -t "${IMAGE}" .
            docker push "${IMAGE}"
            IMAGE_DIGEST="$(docker image inspect "${IMAGE}" --format '{{join .RepoDigests "\n"}}' | grep '@sha256:' | sed -n '1s|.*@||p')"
            test -n "${IMAGE_DIGEST}" || { echo "failed to resolve image digest for ${IMAGE}"; exit 1; }
            (
              cd "${TMP_DIR}"
              ./scripts/set-backend-rust-release.sh "${service}" "${IMAGE_DIGEST}"
            )
          done <<'SERVICES'
          catering-services|apps/catering_services
          companies|apps/companies
          cron|apps/cron
          customers|apps/customers
          developers|apps/developers
          employees|apps/employees
          fitness-trainers|apps/fitness_trainers
          gateway|apps/gateway
          graphic-designers|apps/graphic_designers
          job-seekers|apps/job_seekers
          jobs|apps/jobs
          makeup-artists|apps/makeup_artists
          payments|apps/payments
          photographers|apps/photographers
          social-media-managers|apps/social_media_managers
          tutors|apps/tutors
          ugc-content-creators|apps/ugc_content_creators
          users|apps/users
          video-editors|apps/video_editors
SERVICES
          cd "${TMP_DIR}"
          git config user.name "forgejo-actions"
          git config user.email "forgejo-actions@nxtgauge.com"
          git add apps/nxtgauge-backend-rust/overlays/prod/backend-release-state.tsv apps/nxtgauge-backend-rust/overlays/prod/release-patches.yaml apps/nxtgauge-backend-rust/overlays/prod/disabled-deployments.yaml
          git diff --cached --quiet && exit 0
          git commit -m "chore(gitops): deploy backend@${{ github.sha }}"
          for attempt in 1 2 3 4 5; do
            git -c http.extraHeader="AUTHORIZATION: basic ${AUTH}" pull --rebase origin main
            if git -c http.extraHeader="AUTHORIZATION: basic ${AUTH}" push origin main; then
              exit 0
            fi
            sleep "$attempt"
          done
          echo "failed to push GitOps update after retries"
          exit 1
