#!/bin/bash

agent_server=$1
backend_api=$2
agent_hub_uri=$3
agent_id=$4
deployment_id=$5
is_os_deployment=$6

#region Initialization
script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd "$script_dir" || return
agent_root="/opt/colibri/agent"
common_dir="${script_dir}/common"
service_repo_port=5001
base_url=${agent_server%/}
ca_url="${base_url//https/http}:$service_repo_port/service_repo/agent/ca/colibriCA.crt"
ca_target_path="/etc/pki/ca-trust/source/anchors/colibriCA.crt"
source_list_endpoint="${backend_api%/}/sourcelist/platform"
include_dir="${common_dir}/include"
validation_dir="${common_dir}/validation"
log_dir="/var/log/colibri/agent_push"
log="${log_dir}/installation_${agent_id}.log"
os_info=$(cat /etc/os-release)
os_id=$(echo "$os_info" |  sed -n 's/^ID=\(.*\)$/\1/p' | sed -e 's/^"//' -e 's/"$//')
version_id=$(echo "$os_info" |  sed -n 's/^VERSION_ID=\(.*\)$/\1/p' | sed -e 's/^"//' -e 's/"$//')
os_arch=$(uname -m)
os_name="$os_id $version_id ($os_arch)"

[ -z "$is_os_deployment" ] && is_os_deployment=false

# Define Platform ID
# 1 - Windows
# 2 - Linux_Deb
# 3 - Linux_Rpm
# 4 - Linux_Alt
platform_id=3

#endregion Initialization

#region Functions
function Write_Log {
	message=$1
	severity=$2

	if [ "$severity" == "" ]; then severity="INFO"; fi
	timestamp=$(date --iso-8601=ns | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
	log_line="[$timestamp][${severity^^}]: $message"
	echo -e "$log_line" | tee -a "$log"
}

#endregion Functions

# Prepare install dir
if [ ! -f "$log_dir" ]
then
        mkdir -p "$log_dir" > /dev/null
fi

Write_Log "Installing on [$os_name]"
Write_Log "Initialization started"

Write_Log "Dot source common functions"
for include in "$include_dir"/*.sh
do
		# shellcheck source=/dev/null
        . "$include"
done
Write_Log "Initialization finished"

Write_Log "### ### ###"
Write_Log "## Agent Server	: ${agent_server}"
Write_Log "## Backend API	: ${backend_api}"
Write_Log "## Agent ID		: ${agent_id}"
Write_Log "## Deployment ID	: ${deployment_id}"
Write_Log "## Is OS Deploy	: ${is_os_deployment}"
Write_Log "### ### ###"

Write_Log "Installing CA certificate"
Run_Command "[ -f $ca_target_path ] &&  rm -f $ca_target_path"
Run_Command "wget $ca_url -O $ca_target_path"
Run_Command "update-ca-trust"

Write_Log "Create service repo source list"
Install_Service_Repo "$source_list_endpoint" "$platform_id"

Write_Log "Update YUM cache"
Run_Command "yum makecache"

Write_Log "Test if colibri minion installed"
query=$(rpm -qi "colibri-minion" 2>/dev/null | grep "Install Date")
if [ -n "$query" ]
then
	Write_Log "Colibri minion installed, removing..."
	Run_Command "yum remove -y colibri-minion colibri"
fi

Write_Log "Cleanup colibri minion leftovers"
if [ -d "/opt/colibri/minion" ]
then
	Write_Log "Remove minion scripts folder..."
	Run_Command "rm -rf /opt/colibri/minion"
fi
if [ -f "/opt/colibri/inventory.json" ]
then
	Write_Log "Remove old inventory file..."
	Run_Command "rm -f /opt/colibri/inventory.json"
fi
if [ -f "/opt/colibri/inventory.sh" ]
then
	Write_Log "Remove old inventory script..."
	Run_Command "rm -f /opt/colibri/inventory.sh"
fi

Write_Log "Install Colibri Agent"
agent_out=$(Install_Yum "colibri-agent")
agent_rc=$?
if [ $agent_rc -eq 0 ]
then
	Write_Log "Update agent settings"
	config_out=$(Config_Agent "$agent_root" "$agent_server" "$agent_hub_uri")
	config_rc=$?
	if [ $config_rc -ne 0 ]
	then
		Write_Log "Agent configuration failed with error: [$config_out]" "ERROR"
		exit $config_rc
	fi
else
	Write_Log "Agent installation failed with error: [$agent_out]" "ERROR"
	exit $agent_rc
fi

Write_Log "Init Agent"
Init_Agent "$is_os_deployment" "$agent_root" "$agent_id" "$deployment_id"
init_agent_rc=$?
if [ $init_agent_rc -eq 0 ]
then
	Write_Log "Validate installation"
	validation_report=$(Validate_Agent_Installation "$validation_dir")
	validation_result=$?
	Write_Log "\n$validation_report"
else
	Write_Log "Deployment completed with error, exit code: [$init_agent_rc]" "ERROR"
	validation_result=$init_agent_rc
fi

Write_Log "Done with rc: $validation_result"
exit $validation_result
