---
# ConfigMap with build script that extracts git commit info
apiVersion: v1
kind: ConfigMap
metadata:
  name: build-on-push-script
  namespace: default
data:
  build.sh: |
    #!/bin/bash
    set -e

    echo "===== Neon Vortex Build Triggered by Git Push ====="

    # Get latest commit info from git
    cd /workspace
    GIT_COMMIT=$(git rev-parse HEAD)
    GIT_SHORT_COMMIT=$(git rev-parse --short HEAD)
    GIT_MESSAGE=$(git log -1 --pretty=%B)

    echo "Commit: $GIT_COMMIT"
    echo "Short: $GIT_SHORT_COMMIT"
    echo "Message: $GIT_MESSAGE"

    # Create unique job name
    TIMESTAMP=$(date +%s)
    JOB_NAME="neon-vortex-build-${GIT_SHORT_COMMIT}-${TIMESTAMP}"

    echo "Creating build job: $JOB_NAME"

    # Create the build job
    cat <<EOF | kubectl apply -f -
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: $JOB_NAME
      namespace: default
      labels:
        app: neon-vortex
        build-type: webhook
        git-commit: "$GIT_SHORT_COMMIT"
      annotations:
        git-commit-full: "$GIT_COMMIT"
        git-message: "$GIT_MESSAGE"
    spec:
      ttlSecondsAfterFinished: 7200
      backoffLimit: 1
      template:
        metadata:
          labels:
            app: neon-vortex
            build-type: webhook
        spec:
          restartPolicy: Never
          initContainers:
          - name: git-clone
            image: alpine/git:latest
            command:
            - sh
            - -c
            - |
              echo "Cloning repository..."
              git clone http://192.168.1.49:13001/admin/neon-vortex.git /workspace
              cd /workspace
              git checkout $GIT_COMMIT
              echo "Checked out commit: $GIT_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:$GIT_SHORT_COMMIT"
            - "--cache=true"
            - "--cache-repo=images.caffeinetux.com/apps/neon-vortex/cache"
            - "--label=git.commit=$GIT_COMMIT"
            - "--label=git.message=$GIT_MESSAGE"
            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 $JOB_NAME created successfully!"

    # Send notification
    curl -X POST https://notify.caffeinetux.com \
      -H "Authorization: Bearer APMvTuncQJmm6vd" \
      -H "Content-Type: application/json" \
      -d "{\"title\":\"Neon Vortex Build Started\",\"message\":\"Building commit $GIT_SHORT_COMMIT: $GIT_MESSAGE\",\"priority\":3}" \
      || echo "Notification failed (non-critical)"
---
# Kustomization that triggers on every git push
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: neon-vortex-build-trigger
  namespace: flux-system
spec:
  interval: 30s
  retryInterval: 1m
  timeout: 5m
  sourceRef:
    kind: GitRepository
    name: neon-vortex
    namespace: flux-system
  path: ./
  prune: false
  targetNamespace: default
  postBuild:
    substitute:
      TRIGGER_TIME: "{{ .FluxReconcileTime }}"
  patches:
    - target:
        kind: Job
        name: flux-triggered-build
      patch: |
        apiVersion: batch/v1
        kind: Job
        metadata:
          name: flux-triggered-build-{{ .FluxReconcileTime | replace ":" "-" | replace "." "-" | lower }}
          namespace: default
        spec:
          ttlSecondsAfterFinished: 600
          template:
            spec:
              serviceAccountName: build-trigger-sa
              restartPolicy: Never
              containers:
              - name: trigger-build
                image: alpine/k8s:1.28.13
                command: ["/bin/bash", "/scripts/build.sh"]
                volumeMounts:
                - name: workspace
                  mountPath: /workspace
                - name: script
                  mountPath: /scripts
              volumes:
              - name: workspace
                emptyDir: {}
              - name: script
                configMap:
                  name: build-on-push-script
                  defaultMode: 0755
---
# Job template (will be created by Kustomization on each reconcile)
apiVersion: batch/v1
kind: Job
metadata:
  name: flux-triggered-build
  namespace: default
spec:
  ttlSecondsAfterFinished: 600
  template:
    spec:
      serviceAccountName: build-trigger-sa
      restartPolicy: Never
      containers:
      - name: trigger-build
        image: alpine/k8s:1.28.13
        command:
        - /bin/bash
        - -c
        - |
          apk add --no-cache git curl

          echo "Cloning repository to check for changes..."
          git clone http://192.168.1.49:13001/admin/neon-vortex.git /workspace
          cd /workspace

          /scripts/build.sh
        volumeMounts:
        - name: workspace
          mountPath: /workspace
        - name: script
          mountPath: /scripts
      volumes:
      - name: workspace
        emptyDir: {}
      - name: script
        configMap:
          name: build-on-push-script
          defaultMode: 0755
