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

jobs:
  build-push-update:
    runs-on: gitea-runner-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: ${{ gitea.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: Update Helm values.yaml for Flux
        run: |
          # 1. Update the image tag in your local Helm chart using sed
          sed -i "s/tag: .*/tag: ${{ gitea.sha }}/g" charts/slashroot/values.yaml

          # 2. Configure the Gitea Bot to commit the change
          git config user.name "Gitea Actions Bot"
          git config user.email "actions@gitea.local"

          # 3. Commit and push the updated values.yaml back to the main branch
          git add charts/slashroot/values.yaml
          git commit -m "chore: update slashroot image tag to ${{ gitea.sha }} [skip ci]"
          git push
