name: Build and Update Flux

on:
  push:
    branches:
      - main
    paths-ignore:
      # CRITICAL: Do not trigger this action if we are just updating the Helm chart,
      # otherwise it will create an infinite loop!
      - "helm/**"

env:
  REGISTRY: git.h0melab.uk
  IMAGE_NAME: git.h0melab.uk/rgcosta/slashroot-cc
  # Change this to your actual Gitea username / infra repo name
  INFRA_REPO: h0melab/infra-cluster-fluxcd

jobs:
  build-push-update:
    runs-on: docker
    steps:
      - name: Checkout Code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Log in to Gitea Container Registry
        uses: docker/login-action@v2
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: |
            ${{ env.IMAGE_NAME }}:${{ gitea.sha }}
            ${{ env.IMAGE_NAME }}:latest

      - name: Checkout Infra Repository Manually
        run: |
          echo "🧹 Cleaning up old workspace..."
          rm -rf infra-workspace

          echo "🚀 Attempting to clone the infrastructure repository..."
          # Using the token directly in the URL to bypass the API and clone over HTTPS
          git clone https://gitea_bot:${{ secrets.INFRA_REPO_TOKEN }}@git.h0melab.uk/${{ env.INFRA_REPO }}.git infra-workspace

          echo "✅ Clone successful! Contents:"
          ls -la infra-workspace

      - name: Update Helm values.yaml for Flux
        run: |
          cd infra-workspace

          echo "--- TARGET FILE BEFORE ---"
          cat charts/slashroot/values.yaml

          # The sed command (Make sure the path matches perfectly!)
          sed -i "s/tag: .*/tag: ${{ gitea.sha }}/g" charts/slashroot/values.yaml

          echo "--- TARGET FILE AFTER ---"
          cat charts/slashroot/values.yaml

          # Set up Git
          git config user.name "Gitea Actions Bot"
          git config user.email "actions@gitea.local"
          git add charts/slashroot/values.yaml

          # Check if there are actually changes to commit
          if git diff --staged --quiet; then
            echo "❌ ERROR: No changes were made! Check if 'tag: ' actually exists in your values.yaml"
            exit 1
          else
            echo "✅ Changes detected! Committing and pushing..."
            git commit -m "BOT: (deploy) slashroot-cc update ${{ gitea.sha }}"
            git push origin main
          fi
