apiVersion: batch/v1
kind: Job
metadata:
  name: ${FQDN}-configure-mongo
  namespace: ${NS}
spec:
  template:
    spec:
      containers:
      - command: [/init/configure-mongo.sh]
        env:
        - name: FQDN
          value: ${FQDN}
        - name: NS
          value: ${NS}
        envFrom:
        - secretRef:
            name: ${FQDN}-app
        - secretRef:
            name: ${FQDN}-mongodb-users
        image: mongo
        imagePullPolicy: IfNotPresent
        name: configure
        volumeMounts:
        - name: init-script
          mountPath: /init/
      volumes:
      - name: init-script
        configMap:
          name: configure-mongo
          defaultMode: 0700
      restartPolicy: Never
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: configure-mongo
data:
  configure-mongo.sh: |
    #!/bin/bash -eux
    export host="mongodb://${MONGODB_USER_ADMIN_USER}:${MONGODB_USER_ADMIN_PASSWORD}@${FQDN}-rs0-0.${FQDN}-rs0.${NS}.svc.cluster.local:27017,${FQDN}-rs0-1.${FQDN}-rs0.${NS}.svc.cluster.local:27017,${FQDN}-rs0-2.${FQDN}-rs0.${NS}.svc.cluster.local:27017/rocketchat?authSource=admin&replicaSet=rs0"
    mongo --host=$host  --eval "db.getSiblingDB('admin');"
    mongo --host=$host --eval "db.getSiblingDB('admin').createUser({user: 'oplog', pwd: \"$MONGO_OPLOG_PASSWORD\", roles: [{role: 'read', db: 'local'}, {role: 'clusterMonitor', db: 'admin'}]});";
    mongo --host=$host --eval "db.getSiblingDB('admin').createUser({user: 'rocketchat',pwd: \"$MONGO_PASSWORD\", roles: [{ role: 'readWrite', db: 'rocketchat' }, {role: 'clusterMonitor', db: 'admin'}]});"

