---
apiVersion: v1
kind: ConfigMap
metadata:
  name: build-trigger-script
  namespace: neonvortex
data:
  trigger-build.sh: |
    #!/bin/bash
    set -e

    # Configuration
    GIT_URL="http://192.168.1.49:13001/admin/neon-vortex.git"
    REPO_DIR="/tmp/repo"
    LAST_COMMIT_FILE="/data/last_commit"

    echo "Checking for new commits..."

    # Clone or update repository
    if [ ! -d "$REPO_DIR" ]; then
      git clone "$GIT_URL" "$REPO_DIR"
    else
      cd "$REPO_DIR"
      git fetch origin main
      git reset --hard origin/main
    fi

    cd "$REPO_DIR"
    CURRENT_COMMIT=$(git rev-parse HEAD)
    SHORT_COMMIT=$(git rev-parse --short HEAD)

    echo "Current commit: $CURRENT_COMMIT"

    # Read last processed commit
    LAST_COMMIT=""
    if [ -f "$LAST_COMMIT_FILE" ]; then
      LAST_COMMIT=$(cat "$LAST_COMMIT_FILE")
      echo "Last processed commit: $LAST_COMMIT"
    fi

    # Check if there are new commits
    if [ "$CURRENT_COMMIT" != "$LAST_COMMIT" ]; then
      echo "New commit detected! Triggering build..."

      # Create a new build job with unique name
      TIMESTAMP=$(date +%s)
      JOB_NAME="build-cron-$SHORT_COMMIT-$TIMESTAMP"

      # Generate build job YAML
      cat <<EOF | kubectl apply -f -
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: $JOB_NAME
      namespace: flux-builds
      labels:
        app: neonvortex
        build-trigger: cronjob
        git-commit: "$SHORT_COMMIT"
    spec:
      ttlSecondsAfterFinished: 1800
      template:
        spec:
          restartPolicy: Never
          initContainers:
          - name: git-clone
            image: alpine/git:latest
            command:
            - sh
            - -c
            - |
              git clone $GIT_URL /workspace
              cd /workspace
              git checkout $CURRENT_COMMIT
            volumeMounts:
            - name: workspace
              mountPath: /workspace
          containers:
          - name: kaniko
            image: gcr.io/kaniko-project/executor:latest
            args:
            - "--dockerfile=/workspace/htlm/Dockerfile"
            - "--context=/workspace/htlm"
            - "--destination=images.caffeinetux.com/apps/neon-vortex:latest"
            - "--destination=images.caffeinetux.com/apps/neon-vortex:$SHORT_COMMIT"
            - "--cache=true"
            - "--cache-repo=images.caffeinetux.com/apps/neon-vortex/cache"
            volumeMounts:
            - name: workspace
              mountPath: /workspace
            - name: docker-config
              mountPath: /kaniko/.docker
          volumes:
          - name: workspace
            emptyDir: {}
          - name: docker-config
            secret:
              secretName: harbor-registry
              items:
              - key: .dockerconfigjson
                path: config.json
    EOF

      echo "Build job created: $JOB_NAME"

      # Update last commit
      echo "$CURRENT_COMMIT" > "$LAST_COMMIT_FILE"
      echo "Updated last commit reference"
    else
      echo "No new commits. Skipping build."
    fi
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: build-trigger-data
  namespace: neonvortex
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 100Mi
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: build-trigger-cron-sa
  namespace: neonvortex
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: build-trigger-cron-role
  namespace: flux-builds
rules:
- apiGroups: ["batch"]
  resources: ["jobs"]
  verbs: ["create", "get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: build-trigger-cron-binding
  namespace: flux-builds
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: build-trigger-cron-role
subjects:
- kind: ServiceAccount
  name: build-trigger-cron-sa
  namespace: neonvortex
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: neon-vortex-build-trigger
  namespace: neonvortex
spec:
  schedule: "*/5 * * * *"  # Check every 5 minutes (backup to webhooks)
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: build-trigger-cron-sa
          restartPolicy: Never
          containers:
          - name: trigger
            image: alpine/k8s:1.28.13
            command: ["/bin/bash"]
            args:
            - -c
            - |
              apk add --no-cache git bash curl
              /scripts/trigger-build.sh
            volumeMounts:
            - name: script
              mountPath: /scripts
            - name: data
              mountPath: /data
          volumes:
          - name: script
            configMap:
              name: build-trigger-script
              defaultMode: 0755
          - name: data
            persistentVolumeClaim:
              claimName: build-trigger-data
