#!/bin/sh
RELEASE=`cat /etc/centos-release`
OSVER="${RELEASE#CentOS Stream release }"
TARGET_EMAIL="$1"
TOMCAT_PACKAGE="tomcat9"
if [ "$OSVER" == "9" ]; then
	TOMCAT_PACKAGE="tomcat"
fi
APP_PACKAGENAME="/ROOT.war"
MANIFEST_PATH="META-INF/MANIFEST.MF"
MANIFEST="MANIFEST.MF"
MANIFEST_VERSION="Implementation-Version"
APP_ENVNAME="/setenv.sh"
MONGODB_PACKAGE="mongodb-org"
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-shared-openssl3"


compare_version() {
  local v1="${1//[$'\t\r\n ']}"
  local v2="${2//[$'\t\r\n ']}"

	IFS='.' read -ra ver1 <<< "$v1"
	IFS='.' read -ra ver2 <<< "$v2"

	for i in {0..3}; do
		local num1=${ver1[$i]:-0}
		local num2=${ver2[$i]:-0}

    if (( 10#$num1 > 10#$num2 )); then
			echo 1
			return 0
    elif (( 10#$num1 < 10#$num2 )); then
			echo -1
			return 0
		fi
	done

	echo 0
	return 0
}

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 ${MONGODB_PACKAGE}
var=$?
if [ "$var" == 0 ]; then
	echo "Install MongoDB"
	if [ "$arch" == "aarch64" ]; then
		sudo cp -af ${MONGO_REPO_ARM} ${YUM_REPO}
		sudo chcon -t system_conf_t ${YUM_REPO}
	else
		sudo cp -af ${MONGO_REPO_X64} ${YUM_REPO}
		sudo chcon -t system_conf_t ${YUM_REPO}
	fi
	sudo yum install -y ${MONGODB_PACKAGE}
fi
se=`getenforce`
if [ "$se" == "Enforcing" ]; then
	echo "Set SELinux Policy for the MongoDB processes."
	sudo semanage port -a -t mongod_port_t -p tcp 27017
fi
sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod

isinstalled ${TOMCAT_PACKAGE}
var=$?
if [ "$var" == 1 ]; then
	echo "Detected Tomcat, checking for any AuthFi APPs."
	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}
fi

if [[ -e ${apppath} && -d ${tomcatbin} && -e ${envpath} ]]; then
  echo "AuthFi APP found, upgrading." 
  export TOMCAT_PATH=${tomcatpath}
  source ${envpath}

  if [ -z "${MONGODB_USER}" ] || [ -z "${MONGODB_CRED}" ]; then
    echo "Please enter the AuthFi database administrator account: "
    read DB_USER
    echo -n "Please enter the AuthFi database administrator password: " && read -s DB_CRED || { stty -echo; read DB_CRED; stty echo; }
    sh -c "sed -i 's/\sMONGODB_USER=.*$/ MONGODB_USER=${DB_USER}/' setenv.sh"
    sh -c "sed -i 's/\sMONGODB_CRED=.*$/ MONGODB_CRED=${DB_CRED}/' setenv.sh"
    sh -c "sudo sed -i 's/\sMONGODB_USER=.*$/ MONGODB_USER=${DB_USER}/' ${envpath}"
    sh -c "sudo sed -i 's/\sMONGODB_CRED=.*$/ MONGODB_CRED=${DB_CRED}/' ${envpath}"
    source {envpath}
  fi

  echo
  echo "Check current version."
  sudo unzip -oqj "${TOMCAT_PATH}/webapps${APP_PACKAGENAME}" "${MANIFEST_PATH}" -d "${CURRENTPATH}"
  OLD=`cat "${CURRENTPATH}/${MANIFEST}" | grep ${MANIFEST_VERSION} | cut -d ' ' -f 2`
  sudo unzip -oqj "${CURRENTPATH}${APP_PACKAGENAME}" "${MANIFEST_PATH}" -d "${CURRENTPATH}"
  NEW=`cat "${CURRENTPATH}/${MANIFEST}" | grep ${MANIFEST_VERSION} | cut -d ' ' -f 2`

  check_version=$(compare_version "${OLD}" "${NEW}")

  if [ "${check_version}" -eq 1 ]; then
  	echo "No update required."
  	exit
  elif [ "${check_version}" -eq -1 ]; then 
  	echo "Updating..."
  else
  	echo "Versions are identical."
  	exit
  fi
	echo
	echo "Overwrite with the new version of AuthFi APP."
	sudo systemctl stop tomcat
	sudo rm -rf ${TOMCAT_PATH}/webapps/ROOT
	echo
	sudo cp -af "${CURRENTPATH}"/ROOT.war ${TOMCAT_PATH}/webapps
	if sudo test -f "${TOMCAT_PATH}/conf/tomcat.conf"; then
        	sudo chcon -t tomcat_var_lib_t ${TOMCAT_PATH}/webapps/ROOT.war
          sudo chown tomcat:tomcat ${TOMCAT_PATH}/webapps/ROOT.war
	fi
	echo
	if sudo test -f "${TOMCAT_PATH}/conf/tomcat.conf"; then
        	sudo chcon -t tomcat_exec_t ${envpath}
        	if ! grep -q setenv.sh "/usr/libexec/tomcat/server"; then
                	sudo sh -c "sed '2 a . /usr/libexec/tomcat/setenv.sh' /usr/libexec/tomcat/server | sudo tee /usr/libexec/tomcat/server"
        	fi
	fi
	echo "Set Tomcat startup options and restart."
	sudo systemctl daemon-reload
	sudo systemctl start tomcat
	sudo systemctl enable tomcat
  echo
	echo "Update finished."
	exit
else
	echo "Tomcat is not installed on the system. Continuing with the installation."	
fi
if [ ! -f setenv.sh ]; then
	echo -e "${RED}Environment variable configuration script (setenv.sh) not found!${NC}"
	exit
fi

echo "Please enter the AuthFi database administrator account: "
read DB_USER
echo -n "Please enter the AuthFi database administrator password: " && read -s DB_CRED || { stty -echo; read DB_CRED; stty echo; }
sh -c "sed -i 's/\sMONGODB_USER=.*$/ MONGODB_USER=${DB_USER}/' setenv.sh"
sh -c "sed -i 's/\sMONGODB_CRED=.*$/ MONGODB_CRED=${DB_CRED}/' setenv.sh"
source "${CURRENTPATH}"/setenv.sh
if [ -z "$SERVER_URL" ]; then
	echo -e "${RED}Please enter the AuthFi server URL in setenv.sh ${NC}"
	exit
fi
if [ -z "$TOMCAT_PATH" ]; then
	echo "Tomcat installation path ($TOMCAT_PATH) is blank. Applying default value."
	export TOMCAT_PATH=/usr/share/tomcat
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
sudo yum -y install ${MONGOSH_PACKAGE}
mongosh <<EOF
use ${MONGODB_NAME}
db.createUser(
  {
    user: "${MONGODB_USER}",
    pwd: "${MONGODB_CRED}",
    roles: [ { role: "dbOwner", db: "${MONGODB_NAME}" } ]
  }
)
EOF
sh -c "sudo sed -i 's/#security:/security:\n  authorization: enabled/g' /etc/mongod.conf"
sudo systemctl restart mongod

echo
echo "Start the installation."
echo
echo "Install OpenJDK 21."
sudo yum -y install ${JAVA_PACKAGE}
echo
echo "Install Nginx."
if command -v nginx > /dev/null 2>&1; then
	echo "Detected Nginx"
else
	sudo yum -y install nginx
fi
echo
echo "Copy web static files." 
sudo cp index.html -af /usr/share/nginx/html/
sudo cp 404.html -af /usr/share/nginx/html/
sudo cp 50x.html -af /usr/share/nginx/html/
sudo chown root:root /usr/share/nginx/html/index.html
sudo chown root:root /usr/share/nginx/html/404.html
sudo chown root:root /usr/share/nginx/html/50x.html
echo
echo "Install Tomcat9." 
if command -v tomcat > /dev/null 2>&1; then
	echo "Detected Tomcat"
	sudo systemctl stop tomcat
else
	sudo dnf -y install ${TOMCAT_PACKAGE}
	sudo dnf -y update ${TOMCAT_PACKAGE}
fi
echo
echo "Stop Tomcat Server."
sudo systemctl stop tomcat
echo
echo "Copy Tomcat configuration files."
if sudo test -f "${TOMCAT_PATH}/conf/tomcat.conf"; then
	sudo cp setenv.sh -af /usr/libexec/tomcat/
	sudo chown root:root /usr/libexec/tomcat/setenv.sh
	sudo chcon -t tomcat_exec_t /usr/libexec/tomcat/setenv.sh
	if ! grep -q setenv.sh "/usr/libexec/tomcat/server"; then
		sudo sh -c "sed '2 a . /usr/libexec/tomcat/setenv.sh' /usr/libexec/tomcat/server | sudo tee /usr/libexec/tomcat/server"
	fi
else
	sudo cp -af ./setenv.sh ${TOMCAT_PATH}/bin
fi
if sudo test -f "${TOMCAT_PATH}/conf/tomcat.conf"; then
	if ! grep -q JWT_SECRET "${TOMCAT_PATH}/conf/tomcat.conf"; then
		echo "Export environment variables."
		echo "MONGODB_URL=\"${MONGODB_URL}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "MONGODB_NAME=\"${MONGODB_NAME}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "MONGODB_USER=\"${MONGODB_USER}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "MONGODB_CRED=\"${MONGODB_CRED}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "SENDGRID_API_KEY=\"${SENDGRID_API_KEY}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "JWT_SECRET=\"${JWT_SECRET}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "HMAC_KEY=\"${HMAC_KEY}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
		echo "API_H_KEY=\"${API_H_KEY}\"" | sudo tee -a ${TOMCAT_PATH}/conf/tomcat.conf
	fi
fi
if sudo test -f "${TOMCAT_PATH}/conf/server.xml"; then
	if ! grep -q rewrite.RewriteValve "${TOMCAT_PATH}/conf/server.xml"; then
		FOUNDLINE=`grep -n "<Host " "${TOMCAT_PATH}/conf/server.xml" | cut -d : -f 1`
		if [ -z "$FOUNDLINE" ]; then
			echo "The configuration file server.xml has been changed. No further configuration is needed."
		else
			echo "Write rewrite.RewriteValve property to server.xml."
			FOUNDLINE_PLUS=$((FOUNDLINE+2))
			sudo cp -af ${TOMCAT_PATH}/conf/server.xml ${TOMCAT_PATH}/conf/server.xml.org
			sudo chcon --reference ${TOMCAT_PATH}/conf/server.xml ${TOMCAT_PATH}/conf/server.xml.org
			sudo sh -c "sed ''"$FOUNDLINE_PLUS"' a <Valve className=\"org.apache.catalina.valves.rewrite.RewriteValve\" />\n' ${TOMCAT_PATH}/conf/server.xml | sudo tee ${TOMCAT_PATH}/conf/server.xml"
			echo "Copy the rewrite.config to Catalina localhost folder."
			sudo cp -af rewrite.config ${TOMCAT_PATH}/conf/Catalina/localhost
			sudo chcon --reference ${TOMCAT_PATH}/conf/server.xml ${TOMCAT_PATH}/conf/Catalina/localhost/rewrite.config
		fi
	fi
	if ! grep -q ErrorReportValve "${TOMCAT_PATH}/conf/server.xml"; then
		FOUNDLINE=`grep -n "<Host " "${TOMCAT_PATH}/conf/server.xml" | cut -d : -f 1`
		if [ -z "$FOUNDLINE" ]; then
			echo "The configuration file server.xml has been changed. No further configuration is needed."
		else
            echo "Write showServerInfo property to server.xml ..."
			FOUNDLINE_PLUS=$((FOUNDLINE+2))
			sudo cp -af ${TOMCAT_PATH}/conf/server.xml ${TOMCAT_PATH}/conf/server.xml.org
			sudo chcon --reference ${TOMCAT_PATH}/conf/server.xml ${TOMCAT_PATH}/conf/server.xml.org
			sudo sh -c "sed ''"$FOUNDLINE_PLUS"' a <Valve className=\"org.apache.catalina.valves.ErrorReportValve\" showReport=\"true\" showServerInfo=\"false\" />\n' ${TOMCAT_PATH}/conf/server.xml | sudo tee ${TOMCAT_PATH}/conf/server.xml"
		fi
	fi
fi

echo
echo "Select JVM for Tomcat."
sudo update-alternatives --set java ${JAVA_PACKAGE}
echo
echo "Initialize the database."
cd "${CURRENTPATH}"
#error_var=$(${CURRENTPATH}/AuthFiConfig/bin/AuthFiConfig)
error_var="$(java -jar "${CURRENTPATH}"/AuthFiConfig-all.jar)"

echo ${error_var}
if echo $error_var | grep -iqF Exception; then
	echo "Failed to initialize the database."
	exit
fi
if echo $error_var | grep -iqF ERROR; then
	echo "Failed to initialize the database."
	exit
fi
if echo $error_var | grep -iqF Error; then
	echo "Failed to initialize the database."
	exit
fi


echo
echo "Database initialization successful."
echo "Overwrite with the new version of AuthFi APP."
sudo rm -rf ${TOMCAT_PATH}/webapps/ROOT
echo
sudo cp -af "${CURRENTPATH}"/ROOT.war ${TOMCAT_PATH}/webapps
if sudo test -f "${TOMCAT_PATH}/conf/tomcat.conf"; then
	sudo chcon -t tomcat_var_lib_t ${TOMCAT_PATH}/webapps/ROOT.war
  sudo chown tomcat:tomcat ${TOMCAT_PATH}/webapps/ROOT.war
fi
echo
echo "Configure firewall rules."
sudo sh -c "firewall-cmd --permanent --zone=public --add-service=http && firewall-cmd --permanent --zone=public --add-service=https && firewall-cmd --reload"
sudo sh -c "firewall-cmd --permanent --zone=public --add-port=8080/tcp --permanent && firewall-cmd --reload"
sudo sh -c "setsebool httpd_can_network_connect on -P"
sudo sh -c "setsebool tomcat_can_network_connect_db on -P"

echo "Restart Nginx and Tomcat."
sudo systemctl daemon-reload
sudo systemctl start tomcat
sudo systemctl enable tomcat
sudo systemctl restart nginx
sudo systemctl enable nginx
echo
echo "Creating Relying Party."
sudo systemctl is-active --quiet tomcat
result=$?
if [ "$result" -eq "0" ]; then
	sleep 30
else
	sleep 20
fi
java -jar AuthFiConfig-all.jar addrp
