name: Build and Push

on:
  push:
    branches:
      - master
      - main
  pull_request:
    branches:
      - master
      - main

env:
  REGISTRY: git.kube2.tricnet.de
  IMAGE_NAME: tho/taskplaner

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=sha,prefix=
            type=ref,event=branch
            type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
          cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max

      - name: Update Helm values with new image tag
        if: github.event_name != 'pull_request'
        run: |
          SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
          sed -i "s/^  tag:.*/  tag: \"${SHORT_SHA}\"/" helm/taskplaner/values.yaml
          git config user.name "Gitea Actions"
          git config user.email "actions@git.kube2.tricnet.de"
          git add helm/taskplaner/values.yaml
          git commit -m "chore: update image tag to ${SHORT_SHA} [skip ci]" || echo "No changes to commit"
          git push || echo "Push failed - may need to configure git credentials"
