#!/usr/bin/env bash
set -euo pipefail

wait_for_file() {
  local path="$1" name="$2" retries="${3:-30}" interval="${4:-2}"
  for _ in $(seq 1 "$retries"); do
    if [ -s "$path" ]; then
      return 0
    fi
    sleep "$interval"
  done
  echo "missing required secret: ${name} (${path})" >&2
  exit 1
}

wait_for_file /vault/secrets/MONGO_INITDB_ROOT_USERNAME "root username"
wait_for_file /vault/secrets/MONGO_INITDB_ROOT_PASSWORD "root password"
wait_for_file /vault/secrets/mongo.kf "replica set keyFile"

export MONGO_INITDB_ROOT_USERNAME="$(cat /vault/secrets/MONGO_INITDB_ROOT_USERNAME)"
export MONGO_INITDB_ROOT_PASSWORD="$(cat /vault/secrets/MONGO_INITDB_ROOT_PASSWORD)"

exec /usr/local/bin/docker-entrypoint.sh "$@"
