#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: test postponed join scripts
## bugs: [51624]
## packages:
##  - univention-join
## roles:
##  - domaincontroller_master
## exposure: dangerous

eval "$(ucr shell)"

# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137

JS_NAME='ucs-test-postponed-joinscripts'
JS_FILE="99${JS_NAME}.inst"
JS_PATH="/usr/lib/univention-install/${JS_FILE}"
JS_FLAG="/tmp/${JS_FILE}.test"
UU_STATUS="/var/lib/univention-updater/univention-updater.status"

cleanup() {
	rm -f "${JS_PATH}"
	cleanup_status
	rm -f "$UU_STATUS"
}

cleanup_status() {
	if [ -f /var/univention-join/status ] ; then
		grep -v "^${JS_NAME}" < /var/univention-join/status > /var/univention-join/status.$$
		mv /var/univention-join/status.$$ /var/univention-join/status
	fi
	rm -f "${JS_FLAG}"
}
# first, get into a clean state
cleanup

# add test join script
cat > "$JS_PATH" <<EOF
#!/bin/bash
VERSION=5
. /usr/share/univention-join/joinscripthelper.lib
joinscript_init
touch "$JS_FLAG"
joinscript_save_current_version
exit 0
EOF
chmod a+x "$JS_PATH"
trap cleanup EXIT

# test 1: UCS 5.0-0 PREUP
cat > "${UU_STATUS}" <<EOF
status=RUNNING
phase=PREUP
next_version=5.0-0
target_version=5.1-99
current_version=4.4-8
type=NET
EOF
univention-run-join-scripts --run-scripts "$JS_FILE" || echo "EXIT STATUS $?"
[ -f "$JS_FLAG" ] && fail_test 1 "Join script should not have been executed in PREUP when updating to UCS 5.0-0."
cleanup_status

# test 2: UCS 5.1-15 POSTUP
cat > "${UU_STATUS}" <<EOF
status=RUNNING
phase=POSTUP
next_version=5.1-15
target_version=5.1-15
current_version=5.1-14
type=NET
EOF
univention-run-join-scripts --run-scripts "$JS_FILE" || echo "EXIT STATUS $?"
[ -f "$JS_FLAG" ] || fail_test 1 "Join script should have been executed in POSTUP when updating to UCS 5.1-15."
cleanup_status

# test 3: UCS 4.4-8 UPDATE
cat > "${UU_STATUS}" <<EOF
status=RUNNING
phase=UPDATE
next_version=4.4-8
target_version=4.4-9
current_version=4.4-7
type=NET
EOF
univention-run-join-scripts --run-scripts "$JS_FILE" || echo "EXIT STATUS $?"
[ -f "$JS_FLAG" ] || fail_test 1 "Join script should have been executed in UPDATE when updating to UCS 4.4-8."
cleanup_status

if [ "${version_version%%.*}" -le 4 ] ; then
	echo "INFO: Skipping last test: only meant for UCS 5.0-0 or higher"
else
	next_pl="$((version_patchlevel+1))"
	# test 4: current version to next version
	cat > "${UU_STATUS}" <<EOF
status=RUNNING
phase=UPDATE
next_version=${version_version}-${next_pl}
target_version=${version_version}-${next_pl}
current_version=${version_version}-${version_patchlevel}
type=NET
EOF
	univention-run-join-scripts --run-scripts "$JS_FILE" || echo "EXIT STATUS $?"
	[ -f "$JS_FLAG" ] && fail_test 1 "Join script should not have been executed in UPDATE when updating to UCS ${version_version}-${next_pl}."
	cleanup_status
fi

exit "$RETVAL"
