---
apiVersion: batch/v1
kind: Job
metadata:
  name: app-domain-updater
  namespace: default
spec:
  template:
    spec:
      containers:
        - args:
            - -c
            - |
              set -e
              DEBIAN_FRONTEND=noninteractive
              apt-get update && apt-get install -y git grep

              git config --global user.name "K8s Domain Updater"
              git config --global user.email "gateway-updater@cluster.local"

              cd /workspace
              echo "Cloning repository: clusterforge"
              git clone http://forge:clusterforge@gitea-http.cf-gitea.svc.cluster.local:3000/forge/clusterforge.git repo
              cd repo

              echo "Searching for files containing 'not-a-domain'..."
              FILES_WITH_NOT_A_DOMAIN=$(grep -r -l --exclude=Job_app-domain-updater.yaml "not-a-domain" . || true)

              if [ -z "$FILES_WITH_NOT_A_DOMAIN" ]; then
                echo "No files found containing 'not-a-domain'"
                exit 0
              fi

              echo "Found files containing 'not-a-domain':"
              echo "$FILES_WITH_NOT_A_DOMAIN"

              echo "Replacing 'not-a-domain' with: $NEW_DOMAIN_NAME"
              for file in $FILES_WITH_NOT_A_DOMAIN; do
                echo "Processing file: $file"
                sed -i "s/not-a-domain/$NEW_DOMAIN_NAME/g" "$file"
                echo "Updated: $file"
              done

              if git diff --quiet; then
                echo "No changes detected - domain might already be updated"
                exit 0
              fi

              git pull
              git add .
              git commit -m "$COMMIT_MESSAGE: Replaced 'not-a-domain' with $NEW_DOMAIN_NAME"

              git remote set-url origin http://forge:clusterforge@gitea-http.cf-gitea.svc.cluster.local:3000/forge/clusterforge.git
              git push origin master

              echo "Successfully replaced 'not-a-domain' with $NEW_DOMAIN_NAME and pushed to master"
          command:
            - /bin/sh
          env:
            - name: FILE_PATH
              value: /
            - name: COMMIT_MESSAGE
              value: updated domain references
            - name: NEW_DOMAIN_NAME
              valueFrom:
                configMapKeyRef:
                  key: DOMAIN
                  name: bloom
          image: ubuntu@sha256:09506232a8004baa32c47d68f1e5c307d648fdd59f5e7eaa42aaf87914100db3 # Original tag: 22.04
          name: domain-updater
          volumeMounts:
            - mountPath: /workspace
              name: workspace
      restartPolicy: Never
      volumes:
        - emptyDir: {}
          name: workspace