#!/bin/sh
if [ -z "$1" ]; then
	echo "Usage: $0 <email address>"
	echo "Example: $0 user@example.org"
	exit 1
fi

RELEASE=`cat /etc/centos-release`
OSVER="${RELEASE#CentOS Stream release }"
TARGET_EMAIL="$1"

APP_ENVNAME="/setenv.sh"
APP_PACKAGENAME="/ROOT.war"
TOMCAT_PACKAGE="tomcat9"
if [ "$OSVER" == "9" ]; then
	TOMCAT_PACKAGE="tomcat"
fi
MONGODB_PACKAGE="mongodb-org"
MONGODB_TEMPS="temps"
arch=`uname -m`
dot="."
JAVA_PACKAGE="java-21-openjdk"
JAVA_PACKAGE+=${dot}
JAVA_PACKAGE+=${arch}

CURRENTPATH=`pwd`
#YUM_REPO="/etc/yum.repos.d/mongodb-org-4.4.repo"
YUM_REPO="/etc/yum.repos.d/mongodb-org-8.0.repo"
MONGO_REPO_X64="mongodb-org-8.0.repo.x86_64"
MONGO_REPO_ARM="mongodb-org-8.0.repo.aarch64"
MONGO_REPO="mongodb-org-8.0.repo"
MONGOSH_PACKAGE="mongodb-mongosh"
MONGOSH_PACKAGE2="mongodb-mongosh-shared-openssl3"
RED='\033[0;31m'
NC='\033[0m'
GREEN='\033[0;32m'
function isinstalled {
	if yum list installed "$@" > /dev/null 2>&1; then
		false
	else
		true
	fi
}

isinstalled ${TOMCAT_PACKAGE}
var=$?
if [ "$var" == 0 ]; then
	echo "TOMCAT not found, exit"
	exit
fi

if [ "$var" == 1 ]; then
	webapps=`rpm -ql ${TOMCAT_PACKAGE} | grep "webapps" | head -1`
	file_preamble=`rpm -ql ${TOMCAT_PACKAGE} | grep "preamble"`
	apppath=${webapps}${APP_PACKAGENAME}
	tomcatbin=`echo ${file_preamble} | awk '{print substr( $0, 1, length($0)-9 )}'`
	tomcatpath=`echo ${webapps} | awk '{print substr( $0, 1, length($0)-8 )}'`
	envpath=${tomcatbin}${APP_ENVNAME}
	source ${envpath}
fi

isinstalled ${MONGOSH_PACKAGE}
var=$?
if [ "$var" == 0 ]; then
	isinstalled ${MONGOSH_PACKAGE2}
	var=$?
	if [ "$var" == 0 ]; then
		echo "MONGOSH not found, exit"
		exit
	fi
fi

if [ -z "${MONGODB_USER}" ] || [ -z "${MONGODB_CRED}" ]; then
	echo -e "No DB environment variables!"
	exit
fi

if [ -z "$MONGODB_URL" ]; then
	echo -e "${RED}Please enter the MongoDB URL (MONGODB_URL) in setenv.sh ${NC}"
	exit
fi
if [ -z "$MONGODB_NAME" ]; then
	echo -e "${RED}Please enter the MongoDB database name (MONGODB_NAME) in setenv.sh ${NC}"
	exit
fi

if [[ -e ${apppath} && -d ${tomcatbin} && -e ${envpath} ]]; then
  MONGODB_HOST="${MONGODB_URL#mongodb://}"
  MONGO_URI="mongodb://${MONGODB_USER}:${MONGODB_CRED}@${MONGODB_HOST}/${MONGODB_NAME}"
  CODE=$(mongosh "${MONGO_URI}" --eval "
  	const docs = db.getCollection('${MONGODB_TEMPS}').find(
  		{ email: '${TARGET_EMAIL}' },
  		{ code: 1, _id: 0 }
  	).sort({ expires: -1 }).limit(1).toArray();

  	const result = docs.length > 0 ? docs[0] : null;

  	if (result && result.code) {
  		result.code;
  	} else {
  		'';
  	}
  ")
	if [ -n "${CODE}" ]; then
		echo "The verification code for email ${TARGET_EMAIL} is ${CODE}"
	else
		echo "Error: No code found for email ${TARGET_EMAIL}"
	fi
fi
