name: Build and Push Docker Images

on:
  push:
    branches:
      - main
    paths:
      - 'apps/worker/**'
      - 'apps/api/**'
      - 'apps/web/**'
      - 'apps/nextgen/**'
      - 'apps/nextgen-dev/**'
      - 'apps/nextgen-main/**'
      - 'apps/musicseerr/**'
      - 'k8s/nextgen/**'

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        component: [worker, api, web, nextgen, musicseerr]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITEA_TOKEN }}

      - name: Set up Docker config
        run: |
          mkdir -p .docker
          AUTH=$(echo -n "frankchine:${{ secrets.DOCKERHUB_TOKEN }}" | base64 | tr -d '\n')
          echo "{\"auths\":{\"https://index.docker.io/v1/\":{\"auth\":\"$AUTH\"},\"docker.io\":{\"auth\":\"$AUTH\"}}}" > .docker/config.json

      - name: Build and Push with Kaniko
        uses: docker://gcr.io/kaniko-project/executor:debug
        with:
          args: >-
            --context=dir://${{ gitea.workspace }}/apps/${{ matrix.component }}
            --dockerfile=${{ gitea.workspace }}/apps/${{ matrix.component }}/Dockerfile
            --destination=frankchine/geocrop-${{ matrix.component }}:${{ gitea.sha }}
            --destination=frankchine/geocrop-${{ matrix.component }}:latest
            --cache=true
            --snapshot-mode=redo
            --use-new-run
        env:
          DOCKER_CONFIG: ${{ gitea.workspace }}/.docker

  deploy:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITEA_TOKEN }}

      - name: Update Manifests
        run: |
          cd k8s/base
          # Install kustomize if not present
          if ! command -v kustomize &> /dev/null; then
            curl -s "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" | bash
            chmod +x kustomize
            mv kustomize /usr/local/bin/
          fi
          
          kustomize edit set image frankchine/geocrop-api=frankchine/geocrop-api:${{ gitea.sha }}
          kustomize edit set image frankchine/geocrop-worker=frankchine/geocrop-worker:${{ gitea.sha }}
          kustomize edit set image frankchine/geocrop-web=frankchine/geocrop-web:${{ gitea.sha }}
          
          cd ../../
          # Update next-gen chart tag
          sed -i 's/tag: .*/tag: "${{ gitea.sha }}"/' k8s/nextgen/next-gen-chart/values.yaml
          
      - name: Commit and Push
        run: |
          git config --global user.name "Gitea Action"
          git config --global user.email "action@gitea.com"
          git add k8s/base/kustomization.yaml k8s/nextgen/next-gen-chart/values.yaml
          git commit -m "ci: update image tags to ${{ gitea.sha }} [skip ci]" || echo "No changes to commit"
          git push origin main

