# Copyright (C) 2017, Benjamin Drung <benjamin.drung@profitbricks.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

REPO="${0%/*}/testrepo"
PKGS="${0%/*}/testpkgs"
ARCH=${ARCH:-$(dpkg-architecture -qDEB_HOST_ARCH)}
REPREPRO=$(realpath -m "${0%/*}/.." --relative-base=.)/reprepro
VERBOSE_ARGS="${VERBOSE_ARGS-}"

call() {
	command="$@"
	echo "I: Calling $@"
	"$@" || fail "Command '$command' failed with exit code $?."
}

check_db() {
	db_verify $REPO/db/packages.db || fail "BerkeleyDB 'packages.db' is broken."
	db_verify -o $REPO/db/packagenames.db || fail "BerkeleyDB 'packagenames.db' is broken."
}

add_distro() {
	local name="$1"
	if test -e $REPO/conf/distributions; then
		echo >> $REPO/conf/distributions
	fi
	cat >> $REPO/conf/distributions <<EOF
Codename: $name
Architectures: $ARCH source
Components: main non-free
Log: testrepo.log
Tracking: all
EOF
	if test -n "${2-}"; then
		echo "$2" >> $REPO/conf/distributions
	fi
}

clear_distro() {
	rm -f $REPO/conf/distributions
}

create_repo() {
	rm -rf $REPO
	mkdir -p $REPO/conf
	add_distro buster
	mkdir -p $PKGS
	$REPREPRO -b $REPO export
}

# See https://github.com/wting/shunit2/issues/23
if test -n "${TEST_CASES-}"; then
	suite() {
		for testcase in "${TEST_CASES}" ; do
			suite_addTest $testcase
		done
	}
fi
