#!/bin/bash

set -ex

NAMESPACE="domino-platform"

HOST="mongodb-replicaset-0.mongodb-replicaset"

REPLICAS=$(kubectl -n "$NAMESPACE" get statefulset mongodb-replicaset -o jsonpath='{.spec.replicas}')

OPTS="authSource=admin"

if [ $REPLICAS -gt 1 ]; then
  OPTS="$OPTS&replicaSet=rs0"
  for i in $(seq 2 $REPLICAS); do
    HOST="$HOST,mongodb-replicaset-$(($i-1)).mongodb-replicaset";
  done
fi

MONGO_HOSTNAME=$(echo -n mongodb-replicaset-0.mongodb-replicaset && for i in $(seq 2 $REPLICAS); do echo -n ,mongodb-replicaset-$(($i-1)).mongodb-replicaset; done; echo)

set +x

ADMIN_AUTH=$(kubectl get secret -n "$NAMESPACE" -o go-template='{{ printf "%s:%s" (.data.user | base64decode) (.data.password | base64decode) }}' mongodb-replicaset-admin)

kubectl exec -it -n $NAMESPACE mongodb-replicaset-0 -c mongodb-replicaset -- mongo mongodb://$ADMIN_AUTH@$HOST:27017/domino?$OPTS < mongo.js > output.txt
