apiVersion: batch/v1
kind: CronJob
metadata:
  name: guiserver-labeler
  namespace: default
spec:
  schedule: "*/1 * * * *"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: tigergraph-installer
          containers:
          - name: guiserver-labeler
            image: docker.tigergraph.com/tigergraph-k8s-installer:3.4.0
            imagePullPolicy: Always
            command:
            - "/bin/bash"
            - "-c"
            - |
              # Get all hosts
              allhosts_str=$(kubectl get pods -l app=tigergraph -ojson | jq -c '.items | map(. | .metadata) | map(. | .name)');
              IFS=',' read -ra allhosts_raw <<< "$allhosts_str";
              allhosts=()
              for i in "${allhosts_raw[@]}"; do
                if [[ $i =~ (tigergraph-[0-9]+) ]]
                then
                  hostname=${BASH_REMATCH[1]};
                 allhosts+=($hostname)
                fi
              done;
              # Get hosts running GUI server
              guihosts_str=$(kubectl exec -it tigergraph-0 -- /bin/sh -c "/home/tigergraph/tigergraph/app/cmd/gadmin config get GUI.BasicConfig.Nodes  --file ~/.tg.cfg | jq -c 'map(. | .HostID)'");
              IFS=',' read -ra guihosts_raw <<< "$guihosts_str";
              guihosts=()
              for i in "${guihosts_raw[@]}"; do
                if [[ $i =~ m([0-9]+) ]]
                then
                  hostid=${BASH_REMATCH[1]};
                  hostname="tigergraph-"$((hostid-1));
                  kubectl label pods $hostname guiserver=running --overwrite;
                  guihosts+=($hostname)
                fi
              done;
              # Calculate diff and remove flag on these nodes
              diff=(`echo ${allhosts[@]} ${guihosts[@]} | tr ' ' '\n' | sort | uniq -u `)
              for i in "${diff[@]}"; do
                kubectl label pods $i guiserver-;
              done;
          initContainers:
          - name: init-guiserver-labeler
            image: docker.tigergraph.com/tigergraph-k8s-installer:3.4.0
            imagePullPolicy: IfNotPresent
            command:
            - "/bin/sh"
            - "-c"
            - |
              kubectl wait --for=condition=complete --timeout=6h job/installer || exit 0
          restartPolicy: OnFailure
