#!/bin/bash
# MongoDB init script for UniFi Network Application
# Mount at /docker-entrypoint-initdb.d/init-mongo.sh in the mongo container.
# Creates the 'unifi' user with proper roles on databases: unifi, unifi_stat, unifi_audit, unifi_restore
#
# Env vars (set on the mongo container):
#   MONGO_INITDB_ROOT_USERNAME  - root admin user
#   MONGO_INITDB_ROOT_PASSWORD  - root admin password
#   MONGO_USER                  - unifi app user to create
#   MONGO_PASS                  - unifi app user password (raw, NOT URL-encoded)
#   MONGO_DBNAME                - base database name (stat/audit/restore are suffixed)
#   MONGO_AUTHSOURCE            - auth database (typically 'admin')

if which mongosh > /dev/null 2>&1; then
  mongo_init_bin='mongosh'
else
  mongo_init_bin='mongo'
fi
"${mongo_init_bin}" <<EOF
use ${MONGO_AUTHSOURCE}
db.auth("${MONGO_INITDB_ROOT_USERNAME}", "${MONGO_INITDB_ROOT_PASSWORD}")
db.createUser({
  user: "${MONGO_USER}",
  pwd: "${MONGO_PASS}",
  roles: [
    "clusterMonitor",
    { db: "${MONGO_DBNAME}", role: "dbOwner" },
    { db: "${MONGO_DBNAME}_stat", role: "dbOwner" },
    { db: "${MONGO_DBNAME}_audit", role: "dbOwner" },
    { db: "${MONGO_DBNAME}_restore", role: "dbOwner" }
  ]
})
EOF
