#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Checking all UDM NFS options in exports file"
## exposure: dangerous
## packages:
##  - univention-config
##  - univention-directory-manager-tools
##  - univention-nfs-server
## roles-not: [basesystem]
## tags: [basic]
## join: true

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

eval "$(/usr/sbin/univention-config-registry shell)"

## some globals
sharename="$(random_share)"
SHARE_POSITION="cn=shares,$ldap_base"
fqdn="$hostname.$domainname"
etc="/etc/exports"
mapfile -t available_options < <(udm-test shares/share create | awk  '/\(nfs\)/{print $1}')
declare -a tested_options=()

## here we have the udm_option/nfs_value/udm_value
declare -a options=(
	writeable/rw/1
	sync/async/async
	subtree_checking/subtree_check/1
	root_squash/root_squash/1
)

## create share
echo "----create share"
udm-test shares/share create \
	--position="$SHARE_POSITION" \
	--option nfs \
	--set name="$sharename" \
	--set path="/opt/$sharename" \
	--set host="$fqdn" ||
	fail_fast 1 "could not create share"

## delete share even on abnormal exits
trap 'share_remove "$sharename";rm -rf "/opt/${sharename:?}";' INT TERM EXIT
wait_for_replication_and_postrun

echo "----check whether the NFS configuration file exists"
[ -f "$etc" ] ||
	fail_fast 1 "NFS config file $etc not found"

## set NFS options via UDM and check NFS config file
echo "----set options"
for option in "${options[@]}"
do
	IFS=/ read -r udm_option nfs_value udm_value <<<"$option"
	# modify share
	echo "Debug: Options: $option"
	log_and_execute udm-test shares/share modify \
		--dn "cn=$sharename,cn=shares,$ldap_base" \
		--set "$udm_option=$udm_value" ||
		fail_fast 1 "could not set $udm_option to $udm_value"

	tested_options+=("$udm_option")
done
wait_for_replication_and_postrun

## check the nfs conf file
echo "----test the NFS configuration file"
for option in "${options[@]}"
do
	IFS=/ read -r udm_option nfs_value udm_value <<<"$option"
	grep "^\"/opt/${sharename}" "$etc" | grep -q '[ (,"-]/*'"$nfs_value"'[ ),"]' ||
		fail_fast 1 "nfs config file <-> udm settings mismatch udm option: $udm_option nfs options: $nfs_value udm value: $udm_value"
done

## test if we checked all udm nfs options
echo "----check whether all options have been tested"
mapfile -t untested_options < <(comm -23 <(printf '%s\n' "${available_options[@]}" | sort) <(printf '%s\n' "${tested_options[@]}" | sort))
[ -z "${untested_options[*]}" ] ||
	fail_fast 122 "UDM options '${untested_options[*]}' not covered by this test"

exit 0
