#!/bin/bash 

function Install_Apt {
	counter_limit=5
	counter=0
	query=$(dpkg-query -Wf '${db:Status-Status}\n' "$1" 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 [$1] package was not completely installed before - purge it"
			Run_Command "REMOVE_COLIBRI_DB=1 apt-get --yes purge $1"
		elif [[ "$query" == "installed" ]]; then
			Write_Log "The [$1] package was installed before - purge it"
			Run_Command "REMOVE_COLIBRI_DB=1 apt-get --yes purge $1"
		fi
		query=$(dpkg-query -Wf '${db:Status-Status}\n' "$1" 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 [$1] ..."
		install_out=$(Run_Command "apt-get --yes install $1")
		install_rc=$?
		if [ $install_rc -ne 0 ]
		then
			Write_Log "Installation $1 was failed: [$install_out]" "ERROR"
			return $install_rc
		fi
		return 0
	fi
}
