#!/bin/bash
##
## UnicornIDM: Mongo shell for UnicornIDM
## Copyright (c) 2022 SATOH Fumiyasu @ OSSTech Corp., Japan
##
## License: GNU General Public License version 2
##

set -u

perr()
{
  echo "$0: ERROR: $1" 1>&2
}

pdie()
{
  perr "$1"
  exit "${2-1}"
}

## ======================================================================

mongo_home="${XDG_CACHE_HOME-$HOME/.cache}/unicornidm/mongo"
mongorc="$mongo_home/mongorc.js"
mongorc_dir="/opt/osstech/etc/unicornidm/mongorc.d"
mongo="/opt/osstech/libexec/unicornidm/mongosh"
mongo_password_file="/opt/osstech/var/lib/unicornidm/db.password"

mkdir -m 0755 -p -- "$mongo_home"

if [[ ! -s $mongorc || $mongorc -ot $mongo_password_file ]]; then
  IFS= read -r mongo_password <"$mongo_password_file"
  if [[ -z ${mongo_password+set} ]]; then
    pdie "Failed to read password file: $mongo_password_file"
  fi
  mongo_password="${mongo_password//\\/\\\\}"
  mongo_password="${mongo_password//\'/\\\'}"

  (umask 0077 && touch "$mongorc") || exit $?
  cat >"$mongorc" <<-EOF || exit $?
	db = connect('admin');
	db.auth('unicornidm', '$mongo_password');
	db = db.getSiblingDB('unicornidm');

	host = db.serverStatus().host
	prompt = function() {
	    return db + "@" + host + "> "
	}

	print()
	print('Examples:')
	print('show collections')
	print('db.targets.<TARGET>.submissions.find({"status":"executing"})')
	print('db.targets.<TARGET>.submissions.remove({"_id": ObjectId("<XXXX>")})')
	print('db.targets.<TARGET>.operations.remove({"submissionID": ObjectId("<XXXX>")})')
	print('db.cache.backends.<BACKEND>.numbers.find()')
	print('db.cache.backends.<BACKEND>.numbers.deleteOne({"uidNumber": {\$exists: true}})')
	print()
	EOF
fi

mongorcs=("$mongorc")
for rc in "$mongorc_dir"/*.js; do
  [[ -s $rc ]] || continue
  mongorcs+=("$rc")
done

## ======================================================================

exec env HOME="$mongo_home" "$mongo" --norc --nodb --shell "${mongorcs[@]}" "$@"
