name: Build Admin And Update GitOps

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

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DOCKER_HOST: unix:///var/run/docker.sock
    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 and push admin image
        run: |
          set -euo pipefail
          IMAGE="ci.nxtgauge.com/ashwin/nxtgauge-admin-solid:${{ github.sha }}"
          docker build -t "${IMAGE}" .
          docker push "${IMAGE}"

  update-gitops:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Update GitOps admin release
        env:
          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
          IMAGE_REF: ci.nxtgauge.com/ashwin/nxtgauge-admin-solid:${{ github.sha }}
        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}"
          cd "${TMP_DIR}"
          ./scripts/set-app-release.sh admin-solid "${IMAGE_REF}"
          git config user.name "forgejo-actions"
          git config user.email "forgejo-actions@nxtgauge.com"
          git add apps/nxtgauge-admin-solid/overlays/prod/release-patch.yaml
          git diff --cached --quiet && exit 0
          git commit -m "chore(gitops): deploy admin-solid@${{ github.sha }}"
          git -c http.extraHeader="AUTHORIZATION: basic ${AUTH}" push origin main
