---
apiVersion: batch/v1
kind: Job
metadata:
  name: mongo-rs-config
spec:
  template:
    metadata:
      name: mongo-rs-config
    spec:
      initContainers:
        - name: init-mongodb
          image: mongo:latest
          command:
            - /bin/bash
            - -c
            - |-
              until mongosh --eval 'db.runCommand("ping").ok' mongo-0.mongo:27017/test --quiet;
              do
                echo "**** Waiting for MongoDB ...";
                sleep 5;
              done
      containers:
        - name: mongo
          image: mongo:latest
          command:
            - /bin/bash
            - -c
            - |-
              config='{_id : "rs0", members: [{"_id": 0,"host": "mongo-0.mongo","priority": 3 }]}'
              if [ ! $(mongosh mongo-0.mongo --eval "rs.status().ok" --quiet) ]; then
                echo "**** Cluster initiate ..."
                if [ ! $(mongosh mongo-0.mongo --eval "rs.initiate($config).ok" --quiet) ]; then
                  echo "**** Cluster reconfig ..."
                  mongosh mongo-0.mongo --eval "cfg = rs.conf();  cfg.members[0].priority = cfg.members[0].priority + 1; rs.reconfig(cfg, {force: true})"
                fi;
              fi;
      restartPolicy: Never
  backoffLimit: 4