#!/bin/bash 

Install_Agent_Apt() {
	delete_db=$1
	agent_package="colibri-agent"

	[ "${delete_db,,}" == 'true' ] && delete_db_env="REMOVE_COLIBRI_DB=1"
	
	counter_limit=5
	counter=0
	query=$(dpkg-query -Wf '${db:Status-Status}\n' "$agent_package" 2>/dev/null | grep -E "^installed|half-installed")
	while [ -n "$query" ] && [ $counter -lt $counter_limit ]; do
		counter=$((counter+1))
		if [[ "$query" == "half-installed" ]]; then
			Write_Log "The [$agent_package] package was not completely installed before - purge it"
			Run_Command "$delete_db_env apt-get --yes purge $agent_package"
		elif [[ "$query" == "installed" ]]; then
			Write_Log "The [$agent_package] package was installed before - purge it"
			Run_Command "$delete_db_env apt-get --yes purge $agent_package"
		fi
		query=$(dpkg-query -Wf '${db:Status-Status}\n' "$agent_package" 2>/dev/null | grep -E "^installed|half-installed")
	done
	if [ $counter -eq $counter_limit ]; then
		Write_Log "Unable to remove previously installed package"
		return 1
	fi
	if [ -z "$query" ]; then
		Write_Log "Installing [$agent_package] ..."
		install_out=$(Run_Command "apt-get --yes install $agent_package")
		install_rc=$?
		if [ $install_rc -ne 0 ]
		then
			Write_Log "Installation $agent_package was failed: [$install_out]" "ERROR"
			return $install_rc
		fi
		return 0
	fi
}
