#!/bin/sh -ue
echo "* ${0##*/}: Started"
echo "This test is to ensure that the 'Enhances' field includes all relevent packages"
echo "** env"
env
status=PASS

echo "** installing dependencies"
if [ ! -x /usr/bin/command-not-found ]; then
		# also ensure mawk and sed are installed
		apt-get update
		apt-get install --yes mawk sed command-not-found
fi

echo "** updating command-not-found cache"
echo "*** apt-file update"
apt-file update
echo "*** update-command-not-found"
update-command-not-found
echo "*** check it works"
if command-not-found chromium 2>&1 |tee |grep 'apt install chromium'; then
		echo "Seems OK"
else
		echo >&2 "command-not-found not working?"
fi

enhances=" $(awk '/^Enhances:/{shown=1;next}
                 /^Description:/{shown=0}
                  {if (shown==1) {
                    gsub(","," ")
                    printf("%s ",$0) # \n -> space
                  }}' ./debian/control) "


echo "* Starting tests of 'Enhances' field"
echo "Enhances: <$enhances>"
for test in chfn chsh login ssh sshd passwd inetd syslogd hdparm gpm mingetty sendmail ls du named netstat ps pstree crontab top pidof killall basename dirname traceroute rpcinfo date echo env timed in.timed in.identd init in.pop2d in.pop3d write w vdir tar mail biff egrep grep find rlogind lsof slogin cron ifconfig rshd tcpd su fingerd telnetd; do
		pkgs="$(command-not-found --ignore-installed "$test" 2>&1 \
														 | command grep 'apt install' \
														 | command grep -v '<deb name>' \
														 | awk '{print $3 }')"
		case "$test" in
				fingerd|mail|traceroute|rlogind|rshd|write|in.timed|timed|in.identd|in.pop2d|in.pop3d)
				## enhances added by hand as command-not-found does not locate the relevent package - or there are no packages
				;;
				*)
						## other tests look at binaries, so they enhance any
						## debian package providing that binary
						if [ -z "$pkgs" ]; then
								echo "** FAIL: unexpectedly failed to find any packages providing $test. Update test and README.source"
								status=FAIL
						else
								for deb in $pkgs; do
										case "$enhances" in
												*" $deb "*)
														echo "** PASS: $test would run if $deb is installed and the package has Enhances: $deb"
														;;
												*)
														echo "** FAIL: package should say Enhances: $deb (for test $test)"
														cat ./debian/control || ls -l ./debian
														status="FAIL"
														;;
										esac
								done
						fi
		esac
done
echo "* ${0##*/}: DONE: $status"

if [ "$status" = "FAIL" ]; then
		echo >&2 "FAIL"
		exit 1
else
		echo "PASS"
		exit 0
fi
