#!/usr/bin/env bash
# Generated by 'underpost docker-compose --generate' — do not hand-edit.
set -e

KEYFILE=/opt/keyfile/mongodb-keyfile
RS="${DB_REPLICA_SET:-rs0}"
MEMBER_HOST="mongodb:27017"

if [ ! -s "$KEYFILE" ]; then
    openssl rand -base64 756 > "$KEYFILE"
fi
chmod 400 "$KEYFILE"
chown 999:999 "$KEYFILE"
mkdir -p /data/db
chown -R 999:999 /data/db

# One-time replica-set + root-user bootstrap via the localhost exception,
# performed in the background once mongod accepts loopback connections.
(
    for i in $(seq 1 60); do
        if mongosh --quiet --host 127.0.0.1 --eval 'db.adminCommand({ ping: 1 })' >/dev/null 2>&1; then
            break
        fi
        sleep 1
    done
    
  cat > /tmp/mongo-bootstrap.js <<JS
var RS = "$RS";
var HOST = "$MEMBER_HOST";
var U = "$MONGO_INITDB_ROOT_USERNAME";
var P = "$MONGO_INITDB_ROOT_PASSWORD";
function waitPrimary() {
  for (var i = 0; i < 60; i++) {
    var h = db.hello();
    if (h.isWritablePrimary) return true;
    sleep(1000);
  }
  return false;
}
var initialized = false;
try {
  var s = rs.status();
  if (s && s.ok === 1) initialized = true;
} catch (e) {
  var m = String(e);
  if (m.indexOf("requires authentication") >= 0 || m.indexOf("not authorized") >= 0 || m.indexOf("Unauthorized") >= 0) {
    initialized = true;
  } else if (m.indexOf("NotYetInitialized") < 0 && m.indexOf("no replset config") < 0) {
    throw e;
  }
}
if (!initialized) {
  rs.initiate({ _id: RS, members: [{ _id: 0, host: HOST }] });
  waitPrimary();
  var admin = db.getSiblingDB("admin");
  try {
    admin.createUser({ user: U, pwd: P, roles: [{ role: "root", db: "admin" }] });
    print("BOOTSTRAP_USER_CREATED");
  } catch (e) {
    var s2 = String(e);
    if (s2.indexOf("already exists") < 0 && s2.indexOf("not authorized") < 0 && s2.indexOf("requires authentication") < 0) {
      throw e;
    }
    print("BOOTSTRAP_USER_SKIP");
  }
  print("BOOTSTRAP_DONE");
} else {
  print("BOOTSTRAP_ALREADY_INITIALIZED");
}
JS
    
    mongosh --quiet --host 127.0.0.1 /tmp/mongo-bootstrap.js > /tmp/mongo-bootstrap.log 2>&1 || true
) &

exec gosu mongodb mongod \
--replSet "$RS" --auth --clusterAuthMode keyFile --keyFile "$KEYFILE" --bind_ip_all