#!/bin/bash


echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mCAPI INSTALLER SCRIPT VERSION 2.19 (September 3rd, 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"
loggingdir="/etc/exan/logs"
scriptsdir="/etc/exan/scripts"
installerconfigfullpath="$directory/capiinstaller.cfg"

ip=$(hostname -I | awk '{print $1}')
fqdn=$(hostname -f 2>/dev/null)

confportprod=3000
confport2prod=5672
confmngmportprod=15672

confporttest=3001
confport2test=5673
confmngmporttest=15673

rabbituser="axium"
#rabbitpass=$(LC_ALL=C tr -dc 'A-Za-z0-9!?%=' < /dev/urandom | head -c 12) #Has special chars
rabbitpass=$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 12)

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 CAPI configuration file: $IS_EXISTING_CONFIGURATION"
	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"
	fi
	
	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_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
}

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


}

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" || "$OS_NAME" == "rocky" ) ]]; 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" || "$OS_NAME" == "rocky" ) ]]; 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 --------------------------------------


echo -e "\e[1;96mSet the version of CAPI 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;
confport2=$confport2prod;
confmngmport=$confmngmportprod;
else
confport=$confporttest;
confport2=$confport2test;
confmngmport=$confmngmporttest;
fi

echo -e "\e[1;32mConfiguring $envname instance.\e[0m"

echo " "
echo " "


# ------------------------------- MISC Conf Settings -----------------------------------------


confirmation=0

while ! [[ "$confirmation" = "Y" || "$confirmation" = "QUIT" ]]
do
 
	echo -e "\e[1;96mPlease provide your desired CAPI website address.\e[0m"
	echo -e "\e[1;93mFormat is either hostname or IP. e.g.:\e[0m"	
	echo -e "\e[1;93mHOST.DOMAIN OR XXX.XXX.XXX.XXX\e[0m"	
	confhost=$(prompt_for_value "confhost" "")
	
	echo " "
	
	echo -e "\e[1;96mPlease provide the server IP.\e[0m"	
	echo -e "\e[1;93mThe IP is used to configure the Rabbit Container.\e[0m"
	confhost2=$(prompt_for_value "confhost2" "")
 
	echo " "

	echo -e "\e[1;96mPlease provide your organization ID.\e[0m"
	echo -e "\e[1;93mIf you don't know what your organization ID is please contact axiUm support.\e[0m"
	orgid=$(prompt_for_value "orgid" "")

	echo " "
	
	echo -e "\e[1;96mYou have entered the following:\e[0m"
	echo "Site Address    = $confhost"
	echo "Server IP = $confhost2"
	echo "Organization ID = $orgid"

	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

#------------------------------------ Logging Level for conf ---------------------------------

echo -e "\e[1;96mSelect a detail level for error logging. \e[0m"
echo -e "\e[1;93mEnter [INFO] Log most server interactions. Takes up more space.\e[0m"
echo -e "\e[1;93mEnter [WARN] Only log warnings. Takes up less space.\e[0m"
echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"

conflevel=$(prompt_for_value "conflevel" "WARN")

while ! [[ "$conflevel" = "INFO" || "$conflevel" = "WARN" || "$conflevel" = "QUIT" || "$conflevel" = "DEBUG"  ]] #DEBUG is availible but hidden.
do
	echo -e "\e[1;91mInvalid Input. [INFO/WARN/QUIT]\e[0m"
	conflevel=$(prompt_for_value "conflevel" "")
done

echo " "

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

echo " "
echo " "

# ----------------------------------- 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 connection string.\e[0m"
	echo -e "\e[1;93mFormat is: HOST:PORT/SERVICE_NAME\e[0m"
	confdbconn=$(prompt_for_value "confdbconn" "")
	

	echo " "

	echo -e "\e[1;96mPlease provide your axium WSBI URL.\e[0m"
	confdburl=$(prompt_for_value "confdburl" "")

	echo " "

	echo -e "\e[1;96mYou have entered the following:\e[0m"
	echo "user = $confdbuser"
	echo "pass = $confdbpass"
	echo "conn = $confdbconn"
	echo "URL  = $confdburl"
	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

# ------------------------------- Confirm CareQuality for TEST -----------------------------------

usercq=0
echo -e "\e[1;96mDid you wish to add CareQuality integration to this instance? [Y/N]\e[0m"
echo -e "\e[1;93mEnter [QUIT] to exit.\e[0m"
usercq=$(prompt_for_value "usercq" "")

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

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

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

	confirmation=0
	while ! [[ "$confirmation" = "Y" || "$confirmation" = "QUIT" ]]
	do
		echo " "
		echo -e "\e[1;96mPlease provide your Destnation ID\e[0m"
		echo -e "\e[1;93mThis Field Can be left blank if you do not have a Destination ID. \e[0m" 
		echo -e "\e[1;93mIf the field is blank you may need to re-run the installer at a later time to provide one.\e[0m"
		destinationID=$(prompt_for_value "destinationID" "")
		
		echo " "
		echo -e "\e[1;96mYou have entered the following:\e[0m"
		echo "ID: $destinationID"
		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
	done
fi

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

echo " "
echo " "


#------------------------------- Install with HTTPS? ----------------------------------

httpsinst=0
echo -e "\e[1;96mDid you wish to install CAPI 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 directory for your HTTPS certificate files.\e[0m"
		certdir=$(prompt_for_value "certdir" "")
		certdir=$(strip_double_slashes_in_path $certdir)
		
		echo " "

		echo -e "\e[1;96mPlease provide the filename for your .KEY certificate file.\e[0m"
		echo -e "\e[1;93mPlease include file extention.\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 file extention.\e[0m"
		certfile2=$(prompt_for_value "certfile2" "")

		echo " "

		echo -e "\e[1;96mYou have entered the following:\e[0m"
		echo "Certificate Directory    = $certdir"
		echo "KEY Certificate Filename     = $certfile1"
		echo "CRT Certificate Filename     = $certfile2"
		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 Confirmation -----------------------------------


echo " "
echo " "

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

walletinst=0
echo -e "\e[1;96mDid you wish to install CAPI 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 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


# -------------- rabbit.conf override -----------------------------------
overwriteRabbit=0
createfileRabbit=0

if [[ -f $directory/rabbitmq.conf ]]; then
	echo -e "\e[1;96mrabbitmq.conf already exists. Would you like to overwrite?[Y/N]\e[0m"
	overwriteRabbit=$(prompt_for_value "overwriterabbitconf" "Y")

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



if [[ "$overwriteRabbit" = "Y" ]]; then
	createfileRabbit=1
elif [[ "$overwriteRabbit" = "N" ]]; then
	createfileRabbit=2
fi
 

#------------ Other Container Config -----------------


overwriteEnv=0
createfileEnv=0

if [[ -f $directory/$envname.json ]]; then
	echo -e "\e[1;96m$envname.json already exists. Would you like to overwrite?[Y/N]\e[0m"
	overwriteEnv=$(prompt_for_value "overwriteEnv" "Y")

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


if [[ "$overwriteEnv" = "Y" ]]; then
	createfileEnv=1
elif [[ "$overwriteEnv" = "N" ]]; then
	createfileEnv=2
fi


 
 #debug: To help check parameters.
echo -e "\e[1;92mInstallation Information:\e[0m"
echo " "
echo -e "\e[1;93mDirectories:\e[0m"
echo -e "\e[1;96mFile/Config Directory\e[0m"
echo "$directory"
echo -e "\e[1;96mLogging Directory\e[0m"
echo "$loggingdir"
echo " "
echo -e "\e[1;93mAssigned Ports:\e[0m"
echo -e "\e[1;96mCAPI Port\e[0m"
echo "$confport"
echo -e "\e[1;96mRabbit Port\e[0m"
echo "$confport2"
echo " "
echo -e "\e[1;93mRabbit Credentials:\e[0m"
echo -e "\e[1;96mRabbit User\e[0m"
echo "$rabbituser"
echo -e "\e[1;96mRabbit Pass\e[0m"
echo "$rabbitpass"
echo " "
echo -e "\e[1;92mPlease confirm the following is correct:\e[0m"
echo " "
echo -e "\e[1;93mCAPI Server Information:\e[0m"
echo -e "\e[1;96mCAPI Host Name\e[0m"
echo "$confhost"
echo -e "\e[1;96mServer IP Address\e[0m"
echo "$confhost2"
echo -e "\e[1;96mOrganization ID\e[0m"
echo "$orgid"
echo " "
echo -e "\e[1;96mEnvironment Type:\e[0m"
echo "$envname"
echo -e "\e[1;96mLogging Level:\e[0m"
echo "$conflevel"
echo " "
echo -e "\e[1;93mDatabase Information:\e[0m"
echo -e "\e[1;96mDatabase Username\e[0m"
echo "$confdbuser"
echo -e "\e[1;96mDatabase Password\e[0m"
echo "$confdbpass"
echo -e "\e[1;96mDatabase Connection\e[0m"
echo "$confdbconn"
echo -e "\e[1;96mWSBI URL\e[0m"
echo "$confdburl"
echo " "
echo -e "\e[1;96mCarequality integration:\e[0m"
echo "$usercq"
if [[ "$usercq" = 'Y' ]]; then
	echo -e "\e[1;96mDestinationID:\e[0m"
	echo "$destinationID"
fi
echo " "
echo -e "\e[1;93mHTTPS Details:\e[0m"
echo -e "\e[1;96mInstall with SSL (HTTPS)\e[0m"
echo "$httpsinst"
if [[ "$httpsinst" = "Y" ]]; then
	echo -e "\e[1;96mSSL Certificate Directory\e[0m"
	echo "$certdir"
	echo -e "\e[1;96mKEY Certificate Filename\e[0m"
	echo "$certfile1"
	echo -e "\e[1;96mCRT Certificate Filename\e[0m"
	echo "$certfile2"
	echo " "
fi

if [[ "$walletdir" != "" ]]; then
	echo -e "\e[1;96mWallet Directory Full Path\e[0m"
	echo "$walletdir"
	echo -e "\e[1;96mDatabase timeout (in ms)\e[0m"
	echo "$confdbtimeout"
	echo " "
fi


userconfirm=0
echo -e "\e[1;91mPlease confirm all entered information above is correct. [CONFIRM/ABORT]\e[0m"
read -r userconfirm


while ! [[ "$userconfirm" = "CONFIRM" || "$userconfirm" = "ABORT" ]]
do
	echo -e "\e[1;91mInvalid Input. [CONFIRM/ABORT]\e[0m"
	read -r userconfirm
done

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

echo " "
echo " "

# ------------------------------ Initialzation complete -------------------------------
echo -e "\e[1;95m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mProceeding with system installation/update!\e[0m"
echo -e "\e[1;95m-------------------------------------------------------------------\e[0m"

echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mEnsuring Docker is running...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
sudo systemctl daemon-reload
 
sudo chmod 666 /var/run/docker.sock

echo -e "\e[1;96mStarting Daemons...\e[0m"
sleep 30



#-------------------------------------------------------------------------------------
# Encrypt Password for Config File.
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mEncrypting Password...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
sudo docker pull registry.gitlab.com/scheinone/exan/axium/communication-api/job-utils:$specificdockertag
 
guid="$(uuidgen)"

echo -e "\e[1;91mGenerated Guid:\e[0m"
echo -e "\e[1;91m$guid\e[0m"
 
confdbpasstemp="$(docker run --rm -e AXAPI_KEY="$guid" registry.gitlab.com/scheinone/exan/axium/communication-api/job-utils:$specificdockertag -encrypt "$confdbpass")"
 
confdbpassenc="${confdbpasstemp##*text: }"
 
 
#-------------------------------------------------------------------------------------
# Check Directories for config files
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mChecking Directories...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "


sudo mkdir -p "$loggingdir"
sudo mkdir -p "$scriptsdir"






#------File Creation Rabbit-----
if [[ "$createfileRabbit" = "1" || "$createfileRabbit" = "0" ]]; then
	
	if [[ "$createfileRabbit" = "1" ]]; then
		echo -e "\e[1;93mOverwriting rabbitmq.conf.\e[0m"
		sudo rm $directory/rabbitmq.conf;
		sudo touch $directory/rabbitmq.conf;
	else
		echo -e "\e[1;93mCreating rabbitmq.conf.\e[0m"
	fi
	
	echo -e "default_user=$rabbituser" | sudo tee -a $directory/rabbitmq.conf;
	echo -e "default_pass=$rabbitpass" | sudo tee -a $directory/rabbitmq.conf;
	echo -e "listeners.tcp.default = $confport2" | sudo tee -a $directory/rabbitmq.conf;
	echo -e "management.tcp.port = $confmngmport" | sudo tee -a $directory/rabbitmq.conf
	echo -e "\e[1;93mProcess Complete.\e[0m"
	
elif [[ "$createfileRabbit" = "2" ]]; then
	echo -e "\e[1;96mSkipping Creation/Configuration\e[0m"
fi

echo " "
echo " "

#------File Creation Env JSON-----
if [[ "$createfileEnv" = "1" || "$createfileEnv" = "0" ]]; then
	
	if [[ "$createfileEnv" = "1" ]]; then
		echo -e "\e[1;93mOverwriting $envname.conf.\e[0m"
		sudo rm $directory/"$envname".json

		sudo touch $directory/"$envname".json
	else
		echo -e "\e[1;93mCreating $envname.json.\e[0m"
	fi
	#-----------write to file based on user criteria.------------
	
	echo -e "{																			" | sudo tee -a $directory/"$envname".json;
	echo -e " \"api\": 	{																" | sudo tee -a $directory/"$envname".json
	
	if [[ "$httpsinst" = "Y" ]]; then
		echo -e "			\"baseUri\": \"https://$confhost:$confport/api\",									" | sudo tee -a $directory/"$envname".json										
	else
		echo -e "			\"baseUri\": \"http://$confhost:$confport/api\",									" | sudo tee -a $directory/"$envname".json									
	fi
	
	echo -e "			\"connectBaseUri\": \"$confdburl\"												" | sudo tee -a $directory/"$envname".json;
	echo -e "		},																	" | sudo tee -a $directory/"$envname".json;
	echo -e " \"database\":	{																" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"type\":\"oracle\",														" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"username\": \"$confdbuser\",													" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"password\": \"$confdbpassenc\",												" | sudo tee -a $directory/"$envname".json;
	if [[ "$walletdir" != "" ]]; then
		echo -e "			\"connectString\":\"$confdbconn\",									" | sudo tee -a $directory/"$envname".json;
	else
		echo -e "			\"connectString\":\"$confdbconn?expire_time=5&enable=broken\",									" | sudo tee -a $directory/"$envname".json;
	fi
	echo -e "			\"connection-timeout\":\"$confdbtimeout\",									" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"logging\": [\"ERROR\"]													" | sudo tee -a $directory/"$envname".json;
	echo -e "			},																" | sudo tee -a $directory/"$envname".json




	if [[ "$httpsinst" = "Y" ]]; then
		echo -e " \"server\":	{																" | sudo tee -a $directory/"$envname".json;
		echo -e "			\"https\":	{														" | sudo tee -a $directory/"$envname".json;
 		echo -e "					\"port\": $confport,												" | sudo tee -a $directory/"$envname".json;
		echo -e "					\"keyFile\": \"$certdir/$certfile1\",										" | sudo tee -a $directory/"$envname".json;
		echo -e "					\"certFile\": \"$certdir/$certfile2\"										" | sudo tee -a $directory/"$envname".json;
		echo -e "					}														" | sudo tee -a $directory/"$envname".json;
		echo -e "			},																" | sudo tee -a $directory/"$envname".json
	else
		echo -e " \"server\":	{																" | sudo tee -a $directory/"$envname".json;
		echo -e "			\"http\":	{														" | sudo tee -a $directory/"$envname".json;
 		echo -e "					\"port\": $confport												" | sudo tee -a $directory/"$envname".json;
		echo -e "					}														" | sudo tee -a $directory/"$envname".json;
		echo -e "			},																" | sudo tee -a $directory/"$envname".json

	fi
	
	
	echo -e " \"logger\":	{																" | sudo tee -a $directory/"$envname".json
	
	if [[ "$conflevel" = "WARN" ]]; then
		echo -e "			\"level\": \"warning\"	 													" | sudo tee -a $directory/"$envname".json
	elif [[ "$conflevel" = "DEBUG" ]]; then
		echo -e "			\"level\": \"debug\"														" | sudo tee -a $directory/"$envname".json
	else
		echo -e "			\"level\": \"info\"														" | sudo tee -a $directory/"$envname".json
	fi


	echo -e "		},																	" | sudo tee -a $directory/"$envname".json;
	echo -e " \"rabbitmq\":	{																" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"uri\": \"amqp://$rabbituser:$rabbitpass@$confhost2:$confport2/?heartbeat=60\"					" | sudo tee -a $directory/"$envname".json;	
	
	echo -e "		},																	" | sudo tee -a $directory/"$envname".json;
	echo -e " \"customerId\": \"$orgid\",															" | sudo tee -a $directory/"$envname".json
	
	
	if [[ "$usercq" = "Y" ]]; then
	echo -e " \"redox\":	{																" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"patientSearchExtraFields\": true,												" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"test-mode\": false,														" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"destinationIds\":	{													" | sudo tee -a $directory/"$envname".json;
	echo -e "					\"production\":		{											" | sudo tee -a $directory/"$envname".json;
	echo -e "								\"rls-query-destination\": \"97f2dc1d-c71b-43a7-a436-9b789d44c804\",			" | sudo tee -a $directory/"$envname".json;
	echo -e "								\"organization-query-destination\": \"5d0fd248-6c52-4ad9-b907-ae10bf2dcc39\",		" | sudo tee -a $directory/"$envname".json;
	echo -e "								\"organization_maintenance_destination\": \"5d0fd248-6c52-4ad9-b907-ae10bf2dcc39\",	" | sudo tee -a $directory/"$envname".json;
	echo -e "								\"standard-patient-destination\": \"6391b961-55ae-430b-a789-cf575f03fca0\",		" | sudo tee -a $directory/"$envname".json;
	echo -e "								\"document-query-destination\": \"628cbf79-1156-4923-b9d0-285906160ed6\",		" | sudo tee -a $directory/"$envname".json;
	echo -e "								\"repository-destination-id\": \"$destinationID\"							" >> $directory/"$envname".json;
	echo -e "								}											" | sudo tee -a $directory/"$envname".json;
	echo -e "						}													" | sudo tee -a $directory/"$envname".json;
	echo -e "			},																" | sudo tee -a $directory/"$envname".json
	fi
	
	#Enable IF statement if swagger becomes optional.
	#if [[ "$overwrite" = "Y" ]]; then
	echo -e "\"swagger\":	{																" | sudo tee -a $directory/"$envname".json;
	echo -e "			\"ops-docs\":	{														" | sudo tee -a $directory/"$envname".json;
	echo -e "					\"enabled\": true,												" | sudo tee -a $directory/"$envname".json;
	echo -e "					\"readonly\": false												" | sudo tee -a $directory/"$envname".json;
	echo -e "					}														" | sudo tee -a $directory/"$envname".json;
	echo -e "			}																" | sudo tee -a $directory/"$envname".json;
	#fi
																					
	echo -e "}																			" | sudo tee -a $directory/"$envname".json
		
	#-----------end file-----------
	echo -e "\e[1;93mProcess Complete.\e[0m"
	
elif [[ "$createfileEnv" = "2" ]]; then
	echo -e "\e[1;96mSkipping Creation/Configuration\e[0m"
fi




#-------------------------------------------------------------------------------------
# Install containers.
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mRemoving Old Containers...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
sudo docker stop axium-rabbit-"$envname"
sudo docker rm axium-rabbit-"$envname"

sudo docker stop axium-communication-api-"$envname"
sudo docker rm axium-communication-api-"$envname"

sudo docker stop queue-processor-"$envname"
sudo docker rm queue-processor-"$envname"


#sudo docker image prune -a -f
#sudo docker volume prune -f
#sudo docker network prune -f


sudo docker system prune -f

#-------------------------------------------------------------------------------------
# Rabbit
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mInstalling Rabbit...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
docker pull rabbitmq:3-management 
 
docker container create --hostname axium-rabbit-"$envname" -p $confport2prod:$confport2 --network host --name axium-rabbit-"$envname" --restart always rabbitmq:3-management 
 
sudo docker cp $directory/rabbitmq.conf axium-rabbit-"$envname":/etc/rabbitmq

sudo docker container start axium-rabbit-"$envname"
 
#-------------------------------------------------------------------------------------
# Job Utils
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mCreating Job Utils run script...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
#grab the same version of job utils and lock it in the script
sudo docker pull registry.gitlab.com/scheinone/exan/axium/communication-api/job-utils:$specificdockertag
job_utils_digest=$(docker inspect --format '{{index .RepoDigests 0}}' registry.gitlab.com/scheinone/exan/axium/communication-api/job-utils:$specificdockertag)

#always overwrite the previous job utils script
scriptPath=$scriptsdir/runJobUtils$envname.sh;
if [[ -f $scriptPath ]]; then
	echo -e "\e[1;93mOverwriting $scriptPath.\e[0m"
	sudo rm $scriptPath
fi

echo -e "\e[1;93mCreating $scriptPath.\e[0m"

sudo touch $scriptPath

echo -e "#!/bin/bash" | sudo tee -a $scriptPath;
echo -e "" | sudo tee -a $scriptPath;

#random id for the container to allow rerunning
echo -e "containerName=axium-job-utils-$envname-$(cat /proc/sys/kernel/random/uuid)" | sudo tee -a $scriptPath;

echo -e "sudo docker pull $job_utils_digest"

echo -e "sudo docker container create --name \$containerName --network host --mount type=bind,source=$loggingdir,target=/usr/src/app/logs -e NODE_ENV=\"$envname\" -e DEBUG=app.* -e AXAPI_KEY=\"$guid\" $job_utils_digest \$@" | sudo tee -a $scriptPath;

echo -e "sudo docker cp $directory/"$envname".json \$containerName:/usr/src/app/config" | sudo tee -a $scriptPath;

echo -e "sudo docker start -a \$containerName" | sudo tee -a $scriptPath;
echo -e "sudo docker rm \$containerName" | sudo tee -a $scriptPath;

echo -e "" | sudo tee -a $scriptPath;

sudo chmod +x $scriptPath;
echo -e "\e[1;93mUsage: sudo bash $scriptPath arg1 arg2 \e[0m" 
echo -e "\e[1;93mProcess Complete.\e[0m" 
 
#-------------------------------------------------------------------------------------
# Communication API
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mInstalling Communication API...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
sudo docker pull registry.gitlab.com/scheinone/exan/axium/communication-api/communication-api:$specificdockertag 

if [[ "$httpsinst" = "Y" ]]; then
sudo docker container create --name axium-communication-api-"$envname" -p $confportprod:$confport --network host --mount type=bind,source=$loggingdir,target=/usr/src/app/logs $walletdir --mount type=bind,source="$certdir",target="$certdir" -e NODE_ENV="$envname" -e DEBUG=app.* -e AXAPI_KEY="$guid" --restart always registry.gitlab.com/scheinone/exan/axium/communication-api/communication-api:$specificdockertag
else
sudo docker container create --name axium-communication-api-"$envname" -p $confportprod:$confport --network host --mount type=bind,source=$loggingdir,target=/usr/src/app/logs $walletdir -e NODE_ENV="$envname" -e DEBUG=app.* -e AXAPI_KEY="$guid" --restart always registry.gitlab.com/scheinone/exan/axium/communication-api/communication-api:$specificdockertag
fi

sudo docker cp $directory/rabbitmq.conf axium-communication-api-"$envname":/etc/rabbitmq

sudo docker cp $directory/"$envname".json axium-communication-api-"$envname":/usr/src/app/config 
 
sudo docker container start axium-communication-api-"$envname" 
 
#-------------------------------------------------------------------------------------
# Queue Processor
#-------------------------------------------------------------------------------------
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mInstalling Queue Processor...\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
 
sudo docker pull registry.gitlab.com/scheinone/exan/axium/communication-api/queue-processor:$specificdockertag 

if [[ "$httpsinst" = "Y" ]]; then
sudo docker container create --name queue-processor-"$envname" --network host --mount type=bind,source=$loggingdir,target=/usr/src/app/logs $walletdir --mount type=bind,source="$certdir",target="$certdir" -e NODE_ENV="$envname" -e DEBUG=app.* -e AXAPI_KEY="$guid" --restart always registry.gitlab.com/scheinone/exan/axium/communication-api/queue-processor:$specificdockertag 
else
sudo docker container create --name queue-processor-"$envname" --network host --mount type=bind,source=$loggingdir,target=/usr/src/app/logs $walletdir -e NODE_ENV="$envname" -e DEBUG=app.* -e AXAPI_KEY="$guid" --restart always registry.gitlab.com/scheinone/exan/axium/communication-api/queue-processor:$specificdockertag 
fi

sudo docker cp $directory/"$envname".json queue-processor-"$envname":/usr/src/app/config 
 
sudo docker container start queue-processor-"$envname"
 
echo " "
echo " "
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo -e "\e[1;93mInstall Complete!!!\e[0m"
echo -e "\e[1;93m-------------------------------------------------------------------\e[0m"
echo " "
echo " "
# delete rabbit config here. cleanup.
# sudo rm $directory/rabbitmq.conf;

echo -e "\e[1;93mPlease Securely Save the following information:\e[0m"
echo " "
echo -e "\e[1;93mRabbit Credentials:\e[0m"
echo -e "\e[1;96mRabbit User\e[0m"
echo $rabbituser
echo -e "\e[1;96mRabbit Pass\e[0m"
echo "$rabbitpass"
echo " "
echo " "
echo " "
echo " "
