#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: |
##  Test the correct behavior of univention-updater-check
## roles-not: [basesystem]
## tags:
##  - basic
## packages:
##  - apache2 | apache2-mpm-prefork
## exposure: dangerous
## bugs: [31773]

. pool.sh || exit 137

setup_apache "${repoprefix}"

UPDATE_AVAILABLE=$(ucr get update/available)

FIXED_31733=false
BUG31733 () { # expected-value cmd...
	local expected value
	expected=$1
	shift
	"$@" || return $?
	value="$(ucr get update/available)"
	echo "update/available: $value" >&2

	if ! "${FIXED_31733}" && [ "$expected" != "$value" ]
	then
		echo "BUG #31733: Force APT cache refresh" >&2
		touch /var/lib/dpkg/status
		"$@" || return $?
		value="$(ucr get update/available)"
		echo "update/available: $value" >&2
	fi

	ucr set update/available="$UPDATE_AVAILABLE"
	[ "$expected" = "$value" ]
}

	# break upon error
	set -e

	# initial version numbers
	declare -i patchlevel=0 erratalevel=0 pkversion=1

	# create first repository
	echo "### Initiate the repository (patchlevel=$patchlevel erratalevel=$erratalevel) ###"
	mkpdir "${_version_version}-${patchlevel}" maintained "${ARCH}"
	mkdeb "${pkgname}" ${pkversion} "${ARCH}" "${DIR_POOL}"
	mkpkg "${DIR}" "${DIR_POOL}"

	# reset to X.X-0 without errata patches
	config_repo version/patchlevel=0 version/erratalevel=0

	# install the first version of the test package
	apt-get -qq update
	apt-get -qq install "${pkgname}"
	dpkg-query -W "${pkgname}" | grep -Fqx "${pkgname}	1"

	# no update should be available
	BUG31733 no /usr/share/univention-updater/univention-updater-check

		# create new patchlevel release
		patchlevel+=1
		pkversion+=1
		echo "### Create a new patchlevel release (patchlevel=$patchlevel erratalevel=$erratalevel) ###"
		mkpdir "${_version_version}-${patchlevel}" maintained "${ARCH}"
		mkdeb "${pkgname}" ${pkversion} "${ARCH}" "${DIR_POOL}"
		mkpkg "${DIR}" "${DIR_POOL}"
		python3 create_releases_json.py "${REPODIR}" "${_version_version}-${patchlevel}"

		# an update should be available
		BUG31733 yes /usr/share/univention-updater/univention-updater-check

		# do the update and make sure update/available has been updated
		echo "### Update ###"
		BUG31733 no /usr/share/univention-updater/univention-updater net


		# create new package version in the same release
		pkversion+=1
		echo "### Create a new package version (patchlevel=$patchlevel erratalevel=$erratalevel) ###"
		mkdeb "${pkgname}" ${pkversion} "${ARCH}" "${DIR_POOL}"
		mkpkg "${DIR[2]}" "${DIR_POOL}"
		apt-get -qq update

		# an update should be available
		BUG31733 yes /usr/share/univention-updater/univention-updater-check

		# call univention-actualise and make sure update/available has been updated
		echo "### Updating packages (patchlevel=$patchlevel erratalevel=$erratalevel) ###"
		BUG31733 no /usr/share/univention-updater/univention-actualise
# vim:set ft=sh:
