# apparmor profile adjustments during testing

if command -v aa-enabled > /dev/null; then
	apparmor_enabled=$(test "$(aa-enabled)" = "Yes" && echo true || echo false)
else
	apparmor_enabled=false
fi

_apparmor_check() {
	# allow command to fail if running on Ubuntu-armhf (due to LP: #2008393)
	"$@" && return 0
	_ret=$?

	if [ "$(dpkg-vendor --query Vendor)-$(dpkg --print-architecture)" = "Ubuntu-armhf" ]; then
		echo "WARNING: failed to perform apparmor command: $*" >&2
		echo "On armhf and Ubuntu DEP8 infrastructure, this is not a fatal error." >&2
		echo "See LP: #2008393 for details." >&2
		return 0
	fi

	echo "apparmor command failed: $*" >&2
	exit $_ret
}

_apparmor_cleanup() {
	if [ "$apparmor_enabled" = true ]; then
		echo "reverting apparmor adjustments..."
		sudo rm /etc/apparmor.d/local/usr.sbin.slapd

		if [ -f /etc/apparmor.d/local/usr.sbin.slapd.bak ]; then
			sudo mv /etc/apparmor.d/local/usr.sbin.slapd.bak /etc/apparmor.d/local/usr.sbin.slapd
		fi

		_apparmor_check sudo apparmor_parser -W -T -r /etc/apparmor.d/usr.sbin.slapd
	fi
}

apparmor_setup() {
	# if apparmor is used, allow access to test directory
	if [ "$apparmor_enabled" = true ]; then
		_apparmor_allowdir=$1
		if [ -z "$_apparmor_allowdir" ]; then
			echo "no directory to allow given to apparmor_setup"
			exit 1
		fi
		trap "_apparmor_cleanup" EXIT

		if [ -f /etc/apparmor.d/local/usr.sbin.slapd ]; then
			sudo mv /etc/apparmor.d/local/usr.sbin.slapd /etc/apparmor.d/local/usr.sbin.slapd.bak
		fi

		# this directory is like /etc/slapd
		echo "allowing $_apparmor_allowdir in apparmor..."
		echo "$_apparmor_allowdir/** kwr," | sudo tee -a /etc/apparmor.d/local/usr.sbin.slapd

		_apparmor_check sudo apparmor_parser -W -T -r /etc/apparmor.d/usr.sbin.slapd
	fi
}
