STATUS_URL="http://localhost:8080/status/v1/services/puppetdb-status"
QUERY_URL="http://localhost:8080/pdb/query/v4"

set -e

cleanup () {
	retval=$?
	set +e
	if [ -n "${AUTOPKGTEST_ARTIFACTS}" ]; then
		cp /var/log/puppetdb/puppetdb.log "${AUTOPKGTEST_ARTIFACTS}"
		if [ -d /run/systemd/system ]; then
			journalctl -u puppetdb.service > "${AUTOPKGTEST_ARTIFACTS}/journal.log"
		fi
	fi
	return $retval
}

get_status () {
	curl -s "$STATUS_URL"
}

check_status_var () {
	get_status | jq -e ".status[\"$1\"] == $2" >/dev/null 2>&1
}

query () {
	curl -s "${QUERY_URL}/$1"
}

wait_for_pdb() {
	local state="boot"
	local timeout=120

	for count in $(seq 1 $timeout); do
		case "$state" in
		boot)
			if curl -s --connect-timeout 1 "$STATUS_URL" >/dev/null; then
				state="starting"
				echo "PuppetDB is responding, checking maintenance mode"
				continue
			else
				sleep 1
			fi
			;;
		starting)
			if check_status_var "maintenance_mode?" "false"; then
				echo "Maintenance mode disabled"
				break
			else
				echo "Still in maintenance mode"
				sleep 1
			fi
			;;
		esac
	done
	if [ $count -eq $timeout ]; then
		echo "Timed out"
		exit 1
	fi
}
