name: Mindforge Cronjob Build and Deploy

on:
  push:
    branches:
      - main
    paths:
      - "mindforge.cronjob/**"
      - ".gitea/workflows/**"
  workflow_dispatch: {}

env:
  REGISTRY_HOST: git.ivanch.me
  REGISTRY_USERNAME: ivanch
  IMAGE_CRONJOB: ${{ env.REGISTRY_HOST }}/ivanch/mindforge-cronjob
  KUBE_CONFIG: ${{ secrets.KUBE_CONFIG }}

jobs:
  build_mindforge_cronjob:
    name: Build Mindforge Cronjob Image
    runs-on: ubuntu-22.04

    steps:
      - name: Check out repository
        uses: actions/checkout@v2

      - name: Log in to Container Registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" \
            | docker login "${{ env.REGISTRY_HOST }}" \
                -u "${{ env.REGISTRY_USERNAME }}" \
                --password-stdin

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

      - name: Build and Push Multi-Arch Image
        uses: docker/build-push-action@v6
        with:
          push: true
          context: mindforge.cronjob
          platforms: linux/amd64,linux/arm64
          tags: |
            ${{ env.IMAGE_CRONJOB }}:latest

  deploy_mindforge_cronjob:
    name: Deploy Mindforge Cronjob (internal)
    runs-on: ubuntu-amd64
    needs: build_mindforge_cronjob
    steps:
      - name: Check KUBE_CONFIG validity
        run: |
          if [ -z "${KUBE_CONFIG}" ] || [ "${KUBE_CONFIG}" = "" ] || [ "${KUBE_CONFIG// }" = "" ]; then
            echo "KUBE_CONFIG is not set or is empty."
            exit 1
          fi

      - name: Check out repository
        uses: actions/checkout@v2

      - name: Download and install dependencies
        run: |
          apt-get update -y
          apt-get install -y curl
          curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
          install -m 0755 kubectl /usr/local/bin/kubectl
          kubectl version --client

      - name: Set up kubeconfig
        run: |
          cd mindforge.cronjob/deploy
          echo "$KUBE_CONFIG" > kubeconfig.yaml
        env:
          KUBE_CONFIG: ${{ env.KUBE_CONFIG }}

      - name: Check connection to cluster
        run: |
          cd mindforge.cronjob/deploy
          kubectl --kubeconfig=kubeconfig.yaml cluster-info

      - name: Apply mindforge-cronjob cronjob
        run: |
          cd mindforge.cronjob/deploy
          kubectl --kubeconfig=kubeconfig.yaml apply -f mindforge-cronjob.yaml
