#!/bin/bash


echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mNOTIFICATION INSTALLER SCRIPT 1.0.3 (September 19th, 2025)\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "


# notes: Text colours: Blue 34, Yellow 33, Bright yellow 93, Magenta 35, red 31, bright red 91.

directory="/etc/exan/config/notificationservice"
loggingdir="/etc/exan/logs"
scriptsdir="/etc/exan/scripts"
installerconfigfullpath="$directory/notificationinstaller.cfg"
ip=$(hostname -I | awk '{print $1}')
fqdn=$(hostname -f 2>/dev/null)

confdbtimeout=1200000
ignorepromptforconfig=N

strip_double_slashes_in_path() {
    local input="$1"
    # Replace double slashes with a single slash
    input="${input//\/\//\/}"
    # Replace double backslashes with a single backslash
    input="${input//\\\\/\\}"
	# Remove trailing slashes (either / or \)
    input="${input%/}"
    input="${input%\\}"
    echo "$input"
}

prompt_for_value() {
    local config_key=$1
    local default_value=$2

    # If config file exists, try to read the value from it
    if [[ -f $installerconfigfullpath ]]; then
        local current_value=$(grep "^$config_key=" "$installerconfigfullpath" | cut -d'=' -f2-)
        if [[ -n "$current_value" ]]; then
            default_value=$current_value
        fi
    fi

    # Prompt user for input, prepopulate with default_value if available
    read -r -e -i "$default_value" user_input

    # If user input is empty, use the default_value
    if [[ -z "$user_input" ]]; then
        user_input=$default_value
    fi

    # Use sed to replace the line with the config_key or add it if it doesn't exist
    if grep -q "^$config_key=" "$installerconfigfullpath"; then
        # If key exists, replace the value
        sed -i "s|^$config_key=.*|$config_key=$user_input|" "$installerconfigfullpath"
    else
        # If key doesn't exist, add it
        echo "$config_key=$user_input" >> "$installerconfigfullpath"
    fi
	
	echo "$user_input"
}

check_docker_installed() {

	echo " "
	echo " "
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mChecking pre-requisites: Docker \e[0m"
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "

    if command -v docker >/dev/null 2>&1; then
        echo "Docker is installed:"
        docker --version
		IS_DOCKER_INSTALLED="Y"
    else
        echo "Docker is not installed"
		IS_DOCKER_INSTALLED="N"
		IS_DOCKER_CONTAINER_REGISTRY_SAVED="N"
    fi
}


check_pass_packages_installed_rhel() {
	echo " "
	echo " "
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mChecking pre-requisites (RHEL): Pass Packages \e[0m"
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "
	
	local missing=()
	#gnupg2 and golang packages are default installed in RHEL 9
    local dependencies=(pass git make go jq)
	
	
    for cmd in "${dependencies[@]}"; do
        if ! command -v "$cmd" >/dev/null 2>&1; then
            missing+=("$cmd")
        fi
    done

    if [ ${#missing[@]} -ne 0 ]; then
        echo "Missing dependencies: ${missing[*]}"
		IS_PASS_PACKAGES_INSTALLED="N"
    else
        echo "All dependencies are installed."
        IS_PASS_PACKAGES_INSTALLED="Y"
    fi
}

check_pass_packages_installed_ubuntu() {
	echo " "
	echo " "
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mChecking pre-requisites (Ubuntu): Pass Packages \e[0m"
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "
	
	local missing=()
    local dependencies=(pass jq)
	
	
    for cmd in "${dependencies[@]}"; do
        if ! command -v "$cmd" >/dev/null 2>&1; then
            missing+=("$cmd")
        fi
    done

    if [ ${#missing[@]} -ne 0 ]; then
        echo "Missing dependencies: ${missing[*]}"
		IS_PASS_PACKAGES_INSTALLED="N"
    else
        echo "All dependencies are installed."
        IS_PASS_PACKAGES_INSTALLED="Y"
    fi
}

check_docker_container_registry_saved() {

	echo " "
	echo " "
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mChecking pre-requisites: Valid working Docker Registry Credentials \e[0m"
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "

	# Validate Docker credentials by attempting to authenticate
	echo "[*] Validating Docker login for registry.gitlab.com..."
	output=$(sudo docker-credential-pass list 2>/dev/null)
	status=$?
	
	if [ $status -ne 0 ]; then
		echo "Unable to retrieve any saved credentials, exit status $status."
		IS_DOCKER_CREDENTIALS_VALID=N
		return
	fi
	
	if [[ "$output" == "{}" ]]; then
		echo "Credential store is empty."
		IS_DOCKER_CREDENTIALS_VALID=N
		return
	fi
	
	sudo docker login registry.gitlab.com
	status=$?
	if [ $status -ne 0 ]; then
		echo "Docker container registry credentials failed with exit status $status."
		IS_DOCKER_CREDENTIALS_VALID=N
		return
	fi
	
	IS_DOCKER_CREDENTIALS_VALID=Y
	
}


check_OS() {

	echo " "
	echo " "
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mVerifying compatible environment\e[0m"
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "
	# Check if /etc/os-release exists
	if [ -f /etc/os-release ]; then
		. /etc/os-release
		OS_NAME=$ID
		OS_PRETTY_NAME=$PRETTY_NAME
		OS_VERSION=$VERSION_ID
		OS_CODENAME=$VERSION_CODENAME
	else
		echo "Cannot determine OS: /etc/os-release not found."
		exit 1
	fi

	# Display OS details
	echo "Detected OS: $OS_PRETTY_NAME"
	echo "OS ID: $OS_NAME"
	echo "Version: $OS_VERSION"
	if [ -n "$OS_CODENAME" ]; then
		echo "Codename: $OS_CODENAME"
	fi

	# Additional logic for specific OS types
	case "$OS_NAME" in
		ubuntu)
			echo "This is Ubuntu Linux."
			;;
		debian)
			echo "This is Debian Linux."
			;;
		rhel | redhat)
			echo "This is Red Hat Enterprise Linux."
			;;
		centos)
			echo "This is CentOS. not compatible, exiting."
			exit 1
			;;
		*)
			echo "Unknown or unsupported OS: $OS_NAME"
			;;
	esac

}


summarize_prereq() {
	echo " "
	echo " "
	echo -e "\e[1;95m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mPre-installation summary\e[0m"
	echo -e "\e[1;95m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "
	echo "Operating System (OS): $OS_NAME $OS_VERSION"
	echo "Docker Installation: $IS_DOCKER_INSTALLED"
	echo "Pass Packages: $IS_PASS_PACKAGES_INSTALLED"
	echo "Docker Container Registry saved credentials: $IS_DOCKER_CREDENTIALS_VALID"
	echo "Existing Notification Installer configuration file: $IS_EXISTING_CONFIGURATION"
	
	echo -e "\e[1;95m-------------------------------------------------------------------\e[0m"

	
	if [ "$IS_DOCKER_INSTALLED" = "N" ] || [ "$IS_PASS_PACKAGES_INSTALLED" = "N" ] || [ "$IS_DOCKER_CREDENTIALS_VALID" = "N" ]; then
		echo "Attempting to install or update pre-requisites now..."
	fi
	read -p "Press Enter to continue..."
}

check_existing_config() {

#if config folder doesn't exist, create it
if [ ! -d "$directory" ]; then
  sudo mkdir -p "$directory"
fi

#if config file doesn't exist, create it
if [ ! -f "$installerconfigfullpath" ]; then
    sudo touch "$installerconfigfullpath"
fi

if [ ! -s "$installerconfigfullpath" ]; then
  IS_EXISTING_CONFIGURATION="N"
else
  IS_EXISTING_CONFIGURATION="Y"
fi

} 


install_docker_for_ubuntu() {
echo -e "\e[1;93mAttempting Docker Install.\e[0m"

	dockerinstall=Y;

	sudo apt-get update
	 
	sudo apt-get install ca-certificates curl gnupg
	 
	sudo apt install docker.io

	{
	dockercheck=$(docker -v | cut -d " " -f3)
	} || {
	dockercheck="FAILURE"
	}

	if [ "$dockercheck" = "" ]; then
	dockercheck="FAILURE"
	fi
	if [ "$dockercheck" = "FAILURE" ]; then
	echo -e "\e[1;91mDocker install failed.\e[0m"
	echo -e "\e[1;91mPlease install Docker and try again.\e[0m"
	echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
	echo " "
	echo " "
	echo " "
	exit
	#Install succeeded - wait for processes and daemons to start.
	else
	if [ "$dockerinstall" = "Y" ]; then
	echo -e "\e[1;96mStarting Processes...\e[0m"
	sleep 15
	fi
	echo -e "\e[1;96mDocker installation Successful.\e[0m"
	echo -e "\e[1;96mDocker version = $dockercheck\e[0m"
	echo -e "\e[1;96mProceeding...\e[0m"
	fi
}


install_docker_for_rhel() {

sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

# Install Docker Engine
sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Enable and start Docker
sudo systemctl enable --now docker

if systemctl is-active --quiet docker; then
  echo "Docker has been successfully installed and is running."
else
  echo "Docker installation completed, but the service is not running. Please check the logs."
  echo "Try these three commands:"
  echo "journalctl -u docker.service --no-pager"
  echo "journalctl -xe --no-pager"
  echo "docker info"
  exit 1
fi
}

install_pass_packages_for_rhel() {
echo "Attempting to install pass packages..."
local dependencies=(pass gnupg2 git make go jq golang)

sudo dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
sudo dnf makecache
sudo dnf install -y "${dependencies[@]}"


echo "Attempt to install pass packages complete, setting up keyring"

echo ">>> Generating GPG key for root (if not already present)..."
if ! sudo gpg --batch --list-secret-keys | grep -q 'sec'; then
  cat > /tmp/root-gpg-batch <<EOF
%no-protection
%transient-key
Key-Type: 1
Key-Length: 2048
Name-Real: "axium"
Name-Email: "axium@exansoftware.com"
Expire-Date: 0
%commit
EOF
  sudo gpg --batch --gen-key /tmp/root-gpg-batch
  rm -f /tmp/root-gpg-batch
else
  echo "Root GPG key already exists."
fi

GPG_KEY_ID=$(sudo gpg --list-secret-keys --with-colons | grep '^sec' | head -n1 | cut -d: -f5)
echo ">>> Using GPG Key ID: $GPG_KEY_ID"

echo ">>> Initializing pass for root..."
sudo pass init "$GPG_KEY_ID"

echo ">>> Installing docker-credential-pass..."
if ! command -v docker-credential-pass >/dev/null; then
  TMP_DIR=$(mktemp -d)
  git clone https://github.com/docker/docker-credential-helpers.git "$TMP_DIR"
  pushd "$TMP_DIR"
  sudo cd "$TMP_DIR"
  sudo make pass
  ls -R
  sudo cp bin/build/docker-credential-pass /usr/bin/
  popd
  rm -rf "$TMP_DIR"
else
  echo "docker-credential-pass is already installed."
fi




#echo ">>> Saving Docker registry credentials to pass..."
#CRED_JSON=$(jq -n --arg u "$gituser" --arg p "$gitpass" '{"Username":$u,"Secret":$p}')
#echo "$CRED_JSON" | sudo pass insert -m "docker/registry.gitlab.com"

echo ">>> Configuring Docker for root to use pass..."
DOCKER_CONFIG="/root/.docker/config.json"
sudo mkdir -p "$(dirname "$DOCKER_CONFIG")"
if [[ ! -f "$DOCKER_CONFIG" ]]; then
  echo '{}' | sudo tee "$DOCKER_CONFIG" > /dev/null
fi

if ! sudo jq -e '.credsStore == "pass"' "$DOCKER_CONFIG" > /dev/null 2>&1; then
  sudo jq '. + { "credsStore": "pass" }' "$DOCKER_CONFIG" > /tmp/docker_config.json
  sudo mv /tmp/docker_config.json "$DOCKER_CONFIG"
  echo "Added credsStore: pass to Docker config"
else
  echo "Docker config already uses pass"
fi


}


install_pass_packages_for_ubuntu() {
sudo cat > /tmp/gpg_batch_file <<EOF
%no-protection
%transient-key
Key-Type: 1
Key-Length: 2048
Name-Real: "axium"
Name-Email: "axium@exansoftware.com"
Expire-Date: 0
%commit
EOF
	sudo gpg --batch --gen-key /tmp/gpg_batch_file
	KEY_ID=$(gpg --list-secret-keys --with-colons | grep '^sec' | cut -d: -f5)
	echo -e "Generated GPG Key ID: $KEY_ID"
	sudo rm /tmp/gpg_batch_file
	sudo apt-get -y install pass
	sudo apt install golang-docker-credential-helpers
	sudo apt install jq 
	sudo pass init $KEY_ID

	# Path to Docker config file
	DOCKER_CONFIG="$HOME/.docker/config.json"

	echo ">>> Configuring Docker for root to use pass..."
	DOCKER_CONFIG="/root/.docker/config.json"
	sudo mkdir -p "$(dirname "$DOCKER_CONFIG")"
	if [[ ! -f "$DOCKER_CONFIG" ]]; then
	  echo '{}' | sudo tee "$DOCKER_CONFIG" > /dev/null
	fi

	if ! sudo jq -e '.credsStore == "pass"' "$DOCKER_CONFIG" > /dev/null 2>&1; then
	  sudo jq '. + { "credsStore": "pass" }' "$DOCKER_CONFIG" > /tmp/docker_config.json
	  sudo mv /tmp/docker_config.json "$DOCKER_CONFIG"
	  echo "Added credsStore: pass to Docker config"
	else
	  echo "Docker config already uses pass"
	fi
}

setup_docker_credentials() {

	echo " "
	echo " "
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo -e "\e[1;93mSetting up docker credentials \e[0m"
	echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
	echo " "
	echo " "

echo "Insert GitLab credentials provided to you by the axiUm team"
	echo -e "\e[1;96mEnter gitlab container registry username:\e[0m"
	echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"
	read -r gituser
	if [ "$gituser" = "QUIT" ]; then
		echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
		echo " "
		echo " "
		echo " "
		exit
	fi

	echo -e "\e[1;96mEnter gitlab container registry password:\e[0m"
	echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"
	read -r gitpass

	if [ "$gitpass" = "QUIT" ]; then
		echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
		echo " "
		echo " "
		echo " "
		exit
	fi
	
sudo docker login registry.gitlab.com -u $gituser -p $gitpass

status=$?

	if [ $status -ne 0 ]; then
		echo "Docker container registry credentials failed with exit status. Retry with valid credentials! $status."
		exit 1
	fi

}


# ------------------------------end of all functions--------------------------------------------------

check_OS
check_docker_installed


if [[ "$OS_NAME" == "ubuntu" ]]; then
check_pass_packages_installed_ubuntu
elif [[ "$OS_NAME" == "rhel" ]]; then
check_pass_packages_installed_rhel
fi

# only check the credentials if docker and the pass packages are ready
IS_DOCKER_CREDENTIALS_VALID="N"
if [[ "$IS_DOCKER_INSTALLED" == "Y" && "$IS_PASS_PACKAGES_INSTALLED" == "Y" ]]; then
check_docker_container_registry_saved
fi

# check if a previous config exists or not
check_existing_config

#summary of system state
summarize_prereq


if [[ "$IS_DOCKER_INSTALLED" == "N" && "$OS_NAME" == "ubuntu" ]]; then
echo -e "\e[1;96mAttempting to install Docker for $OS_NAME \e[0m"
install_docker_for_ubuntu
fi

if [[ "$IS_DOCKER_INSTALLED" == "N" && "$OS_NAME" == "rhel" ]]; then
echo -e "\e[1;96mAttempting to install Docker for $OS_NAME \e[0m"
install_docker_for_rhel
fi

if [[ "$IS_PASS_PACKAGES_INSTALLED" == "N" && "$OS_NAME" == "ubuntu" ]]; then
echo -e "\e[1;96mAttempting to install pass packages for $OS_NAME \e[0m"
install_pass_packages_for_ubuntu
fi

if [[ "$IS_PASS_PACKAGES_INSTALLED" == "N" && "$OS_NAME" == "rhel" ]]; then
echo -e "\e[1;96mAttempting to install pass packages for $OS_NAME \e[0m"
install_pass_packages_for_rhel
fi

if [[ "$IS_DOCKER_CREDENTIALS_VALID" == "N" ]]; then
echo -e "\e[1;96mAttempting to setup docker container registry credentials \e[0m"
setup_docker_credentials
fi


#if [[ "$IS_EXISTING_CONFIGURATION" == "Y" ]]; then
#echo -e "\e[1;96mExisting configuration detected: Ignore prompting and automatically use existing? \e[0m"
#ignoreprompting=$(prompt_for_value "ignoreprompting" "N")

# --------------------------------- User Input for Config --------------------------------------



# Colors & icons
YELLOW='\033[1;93m'
CYAN='\033[1;96m'
GREEN='\033[1;92m'
RED='\033[1;91m'
NC='\033[0m'
CHECK="\033[1;92m✅\033[0m"
WARN="\033[1;93m⚠️\033[0m"
ERROR="\033[1;91m❌\033[0m"
INFO="\033[1;96mℹ️\033[0m"
ARROW="\033[1;93m➡️\033[0m"

print_header() {
  printf "${YELLOW}----------------------------------------------------${NC}\n"
  printf "$1\n"
  printf "${YELLOW}----------------------------------------------------${NC}\n"
}


echo -e "\e[1;96mSet the version of Notification Installer to be used (use latest if not otherwise instructed) \e[0m"

specificdockertag=$(prompt_for_value "specificdockertag" "latest")


echo -e "\e[1;96mWhich type of environment should be configured? [TEST/PROD]\e[0m"
echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"

envname=$(prompt_for_value "envname" "")

while ! [[ "$envname" = "PROD" || "$envname" = "TEST" || "$envname" = "QUIT" ]]
do
	echo -e "\e[1;91mInvalid Input. [PROD/TEST/QUIT]\e[0m"
	envname=$(prompt_for_value "envname" "")
done

echo " "

if [ "$envname" = "QUIT" ]; then
	echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
	echo " "
	echo " "
	echo " "
	exit
fi

# - simplify parameters -
if [ "$envname" = "PROD" ]; then
confport=$confportprod;

else
confport=$confporttest;
fi


# NGINX Setup
echo -e "\e[1;96mSet the server URL name (e.g, ex-qaubuntu1.exansoftware.com).\e[0m"
SERVER_NAME=$(prompt_for_value "SERVER_NAME" "")

httpsinst=0
echo -e "\e[1;96mDid you wish to install Notification Service with HTTPS? [Y/N]\e[0m"
httpsinst=$(prompt_for_value "httpsinst" "")
echo " "

while ! [[ "$httpsinst" = "Y" || "$httpsinst" = "N" || "$httpsinst" = "QUIT" ]]
do
	echo -e "\e[1;91mInvalid Input. [Y/N/QUIT]\e[0m"
	httpsinst=$(prompt_for_value "httpsinst" "")
done

if [ "$httpsinst" = "QUIT" ]; then
	echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
	echo " "
	echo " "
	echo " "
	exit
fi

if [ "$httpsinst" = "Y" ]; then

	confirmation=0

	while ! [[ "$confirmation" = "Y" || "$confirmation" = "QUIT" ]]
	do
 
		echo -e "\e[1;96mPlease provide the port for your HTTPS server (default: 5012).\e[0m"
		PORT_HTTPS=$(prompt_for_value "PORT_HTTPS" "5012")

		echo -e "\e[1;96mPlease provide the filename for your .KEY certificate file.\e[0m"
		echo -e "\e[1;93mPlease include full file path and extension e.g /etc/exan/ssl/my_key_file.key\e[0m"
		certfile1=$(prompt_for_value "certfile1" "")
		
		echo -e "\e[1;96mPlease provide the filename for your .CRT certificate file.\e[0m"
		echo -e "\e[1;93mPlease include full file path and extension e.g /etc/exan/ssl/my_key_file.crt\e[0m"
		certfile2=$(prompt_for_value "certfile2" "")
		SSL_KEY_FILENAME=$(basename "$certfile1")
        SSL_CERT_FILENAME=$(basename "$certfile2")
		SSL_DIR=$(dirname "$certfile1")


		echo " "

		echo -e "\e[1;96mYou have entered the following:\e[0m"
		echo "KEY Certificate Filename     = $SSL_KEY_FILENAME"
		echo "CRT Certificate Filename     = $SSL_CERT_FILENAME"
		echo " "

		echo -e "\e[1;96mIs this information Correct? [Y/N]\e[0m"
		echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"
		read -r -e -i "Y" confirmation

		echo " "

		while ! [[ "$confirmation" = "Y" || "$confirmation" = "N" || "$confirmation" = "QUIT" ]]
		do
			echo -e "\e[1;91mInvalid Input. [Y/N/QUIT]\e[0m"
			read -r -e -i "Y" confirmation
		done

	done

	if [ "$confirmation" = "QUIT" ]; then
		echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
		echo " "
		echo " "
		echo " "
		exit
	fi

fi

if [ "$httpsinst" = "N" ]; then
		echo -e "\e[1;96mPlease provide the port for your HTTP server (default: 5003).\e[0m"
		PORT_HTTP=$(prompt_for_value "PORT_HTTP" "5003")
fi

# ----------------------------------- User Input for DB --------------------------------------

confirmation=0

while ! [[ "$confirmation" = "Y" || "$confirmation" = "QUIT" ]]
do
 
	echo -e "\e[1;96mPlease provide your axium Database username.\e[0m"
	confdbuser=$(prompt_for_value "confdbuser" "")
 
	echo " "
 
	echo -e "\e[1;96mPlease provide your axium Database password.\e[0m"
	echo -e "\e[1;91m!!! This password will be encrypted and stored securely !!!\e[0m"
	read -r confdbpass
	
	while [[ -z "$confdbpass" ]]; do
		echo -e "\e[1;91mInvalid Input. DB Password cannot be empty\e[0m"
		echo -e "\e[1;96mPlease provide your axium Database password.\e[0m"
		echo -e "\e[1;91m!!! This password will be encrypted and stored securely !!!\e[0m"
		read -r -e -i "Y" confdbpass
	done
 
	echo " "

	echo -e "\e[1;96mPlease provide your axium Database host.\e[0m"
	confdbhost=$(prompt_for_value "confdbhost" "")
	

	echo " "
	
	echo " "

	echo -e "\e[1;96mPlease provide your axium Database port.\e[0m"
	confdbport=$(prompt_for_value "confdbport" "")
	

	echo " "
	
	echo " "

	echo -e "\e[1;96mPlease provide your axium Database service name. Typically ORCL\e[0m"
	confdbservicename=$(prompt_for_value "confdbservicename" "ORCL")
	

	echo " "



	echo -e "\e[1;96mYou have entered the following:\e[0m"
	echo "user = $confdbuser"
	echo "pass = $confdbpass"
	echo "confdbhost = $confdbhost"
	echo "confdbport = $confdbport"
	echo "confdbservicename = $confdbservicename"
	echo -e "\e[1;96mIs this information Correct? [Y/N]\e[0m"
	echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"
	read -r -e -i "Y" confirmation

	echo " "

	while ! [[ "$confirmation" = "Y" || "$confirmation" = "N" || "$confirmation" = "QUIT" ]]
	do
		echo -e "\e[1;91mInvalid Input. [Y/N/QUIT]\e[0m"
		read -r -e -i "Y" confirmation
	done

done

if [ "$confirmation" = "QUIT" ]; then
	echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
	echo " "
	echo " "
	echo " "
	exit
fi


#------------------------------- Install with Oracle Wallet? ----------------------------------

walletinst=0
echo -e "\e[1;96mDid you wish to install Notification Service with an Oracle Wallet? [Y/N]\e[0m"
walletinst=$(prompt_for_value "walletinst" "")
echo " "

while ! [[ "$walletinst" = "Y" || "$walletinst" = "N" || "$walletinst" = "QUIT" ]]
do
	echo -e "\e[1;91mInvalid Input. [Y/N/QUIT]\e[0m"
	walletinst=$(prompt_for_value "walletinst" "")
done

if [ "$walletinst" = "QUIT" ]; then
	echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
	echo " "
	echo " "
	echo " "
	exit
fi

if [ "$walletinst" = "Y" ]; then

	confirmation=0

	while ! [[ "$confirmation" = "Y" || "$confirmation" = "QUIT" ]]
	do
 
		echo -e "\e[1;96mPlease provide the directory for your wallet files. (Recommended: /usr/lib/oracle/19.18/client64/lib/network/admin if oracle client is installed or /etc/exan/oracle/network/admin if it is not)  \e[0m"
		walletdir=$(prompt_for_value "walletinst" "")
		walletdir=$(strip_double_slashes_in_path $walletdir)

		echo " "
		
		echo -e "\e[1;96mPlease set your database timeout (in ms). (Recommended & default: 120000)  \e[0m"
		confdbtimeout=$(prompt_for_value "confdbtimeout" "120000")

		echo " "


		echo -e "\e[1;96mYou have entered the following:\e[0m"
		echo "Wallet files Directory    = $walletdir"
		echo "Database timeout (in ms)    = $confdbtimeout"
		echo " "

		echo -e "\e[1;96mIs this information Correct? [Y/N]\e[0m"
		echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"
		read -r -e -i "Y" confirmation

		echo " "

		while ! [[ "$confirmation" = "Y" || "$confirmation" = "N" || "$confirmation" = "QUIT" ]]
		do
			echo -e "\e[1;91mInvalid Input. [Y/N/QUIT]\e[0m"
			read -r -e -i "Y" confirmation
		done

	done

	if [ "$confirmation" = "QUIT" ]; then
		echo -e "\e[1;91mEXITING SCRIPT...\e[0m"
		echo " "
		echo " "
		echo " "
		exit
	fi

fi

# ------------------------------ Final Oracle Wallet Confirmation -----------------------------------

if [[ -z $walletdir ]]; then
  walletdir="";
  #echo "walletdir = $walletdir"
else
  walletdir="-v $walletdir:/usr/lib/oracle/19.18/client64/lib/network/admin:ro";
  echo "walletdir = $walletdir"
fi

# ---------------------------------------------------------------------------------------------


# Kafka Config
#echo -e "\e[1;96mSet the kafka server (set to localhost if message broker installed on the same machine)\e[0m"
# KAFKA_BOOTSTRAP_SERVER=$(prompt_for_value "KAFKA_BOOTSTRAP_SERVER" "localhost")
 
echo -e "\e[1;96mSet the kafka username (use the exact value of kafka username set when message broker was installed) \e[0m"
KAFKA_USER=$(prompt_for_value "KAFKA_USER" "kafka-default-user")

echo -e "\e[1;96mSet the kafka password (use the exact value of kafka username set when message broker was installed)\e[0m"
KAFKA_PASSWORD=$(prompt_for_value "KAFKA_PASSWORD" "kafka-default-password")

echo -e "\e[1;96mSet the kafka sever and port:\e[0m"
echo -e "\e[1;96mCurrent IP Address Detected: $ip\e[0m"
if [[ -n "$fqdn" ]]; then
    echo -e "\e[1;96mCurrent FQDN Address Detected: $fqdn\e[0m"
	echo -e "\e[1;96m(set the value to ${fqdn}:29094 unless otherwise instructed)\e[0m"
	KAFKA_SERVER=$(prompt_for_value "KAFKA_SERVER" "$fqdn:29094")
else
echo -e "\e[1;96m(set the value to $ip:29094 unless otherwise instructed)\e[0m"
KAFKA_SERVER=$(prompt_for_value "KAFKA_SERVER" "$ip:29094")
fi



echo -e "\e[1;96mSet the proxy pass port for the nginx server (set to 5251 unless otherwise instructed)\e[0m"
nginx_proxy_pass_port=$(prompt_for_value "nginx_proxy_pass_port" "5251")

# Final Summary
print_header "${YELLOW} Final Summary${NC}"
printf "Server Name       : $SERVER_NAME\n"
printf "HTTP Port         : $PORT_HTTP\n"
if [ "$httpsinst" = "Y" ]; then
  printf "HTTPS Port        : $PORT_HTTPS\n"
  printf "SSL Local Folder  : $SSL_DIR\n"
fi
printf "Kafka host        : $KAFKA_SERVER\n"

printf "%b" "Proceed with container creation? [yes/no]: "
read CONFIRM
[[ "$CONFIRM" != "yes" ]] && { echo -e "$ERROR Cancelled by user."; exit 1; }


# NGINX Config
if [[ "$httpsinst" = "N" ]]; then
cat <<EOF > $directory/nginx.conf
worker_processes 1;
pid /var/run/nginx.pid;

events {
    worker_connections 2000;
}

http {
	access_log /dev/stdout;
	error_log /dev/stderr info;
    server {
        listen $PORT_HTTP;
        server_name $SERVER_NAME;
        location / {
            proxy_pass http://127.0.0.1:$nginx_proxy_pass_port;
            proxy_set_header Host \$host;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
        }
    }
}	
EOF
fi

if [[ "$httpsinst" = "Y" ]]; then
cat <<EOF > $directory/nginx.conf
worker_processes 1;

pid /var/run/nginx.pid;

events {
    worker_connections 2000;
}

http {
	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log debug;
	map \$http_upgrade \$connection_upgrade {
    default upgrade;
    ''      close;
	}
    server {
        listen $PORT_HTTPS ssl;
        server_name $SERVER_NAME;
        ssl_certificate     /etc/nginx/ssl/$SSL_CERT_FILENAME;
        ssl_certificate_key /etc/nginx/ssl/$SSL_KEY_FILENAME;
        ssl_prefer_server_ciphers on;
        ssl_protocols  TLSv1.2 TLSv1.3;
        ssl_ciphers   EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED;
        add_header Strict-Transport-Security "max-age=31536000";
        ssl_session_cache shared:SSL:15m;
        ssl_session_timeout 10m;

        location / {
		    proxy_http_version 1.1;
			proxy_set_header Upgrade \$http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass http://127.0.0.1:$nginx_proxy_pass_port;
            proxy_set_header Host \$host;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
        }
    }
}
EOF
fi


# Container setup
print_header "${YELLOW} Creating Docker Container${NC}"

IMAGE="registry.gitlab.com/scheinone/exan/axium/soa/notification-service/notification-service:$specificdockertag"
CONTAINER_NAME="notification-service-${envname}"

sudo docker pull "$IMAGE"

# Check if container already exists
if sudo docker ps -a --format '{{.Names}}' | grep -Eq "^${CONTAINER_NAME}\$"; then
    echo -e "$INFO Stopping and removing existing container..."
    docker stop "$CONTAINER_NAME" >/dev/null 2>&1 || true
    docker rm "$CONTAINER_NAME" >/dev/null 2>&1 || true
fi



if [[ "$httpsinst" = "Y" ]]; then
CONTAINER_ID=$(docker container create --name "$CONTAINER_NAME" --network host --restart always -v $directory/nginx.conf:/etc/nginx/nginx.conf:ro -v "$SSL_DIR":/etc/nginx/ssl:ro $walletdir -e DB_USER="$confdbuser" -e DB_PASSWORD="$confdbpass" -e DB_HOST="$confdbhost" -e DB_PORT="$confdbport" -e DB_SERVICE="$confdbservicename" -e KAFKA_BOOTSTRAP_SERVER="$nginx_proxy_pass_port" -e NOTIFICATION_APP_PORT="$nginx_proxy_pass_port" -e KAFKA_USER="$KAFKA_USER" -e KAFKA_PASSWORD="$KAFKA_PASSWORD" -e KAFKA_SERVER="$KAFKA_SERVER" -e USE_HTTPS=false "$IMAGE")
else
CONTAINER_ID=$(docker container create --name "$CONTAINER_NAME" --network host --restart always -v $directory/nginx.conf:/etc/nginx/nginx.conf:ro $walletdir -e DB_USER="$confdbuser" -e DB_PASSWORD="$confdbpass" -e DB_HOST="$confdbhost" -e DB_PORT="$confdbport" -e DB_SERVICE="$confdbservicename" -e KAFKA_BOOTSTRAP_SERVER="$nginx_proxy_pass_port" -e KAFKA_USER="$KAFKA_USER" -e KAFKA_PASSWORD="$KAFKA_PASSWORD" -e KAFKA_SERVER="$KAFKA_SERVER" -e USE_HTTPS=false "$IMAGE")
fi


sudo docker container start "$CONTAINER_ID"
echo -e "Notification Installation complete"