# -*- shell-script -*-

FUNCTIONS_DIR="debian/tests/functions.d"

match_or_exit () {
	file_to_match="$1"
	pattern_file="$2"

	while read line_to_match <&3 && read pattern_line <&4 ; do
		if [ "${line_to_match##$pattern_line}" ]; then
			echo '!!! MISMATCH !!!' >&2
			echo "Line:    ${line_to_match}" >&2
			echo "Pattern: ${pattern_line}" >&2
			exit 1
		fi;
	done 3<"${file_to_match}" 4<"${pattern_file}"
}

stop_strongswan_networking () {
	systemctl stop strongswan-starter.service
	systemctl stop networking.service
}

configure_and_start_networking () {
	#Add interfaces needed for the test
	cat ${FUNCTIONS_DIR}/add-to.interfaces >> /etc/network/interfaces
	systemctl start networking.service
}

configure_and_start_strongswan () {
	cp ${FUNCTIONS_DIR}/charon.conf /etc/strongswan.d/
	cp ${FUNCTIONS_DIR}/ipsec.conf /etc/
	cp ${FUNCTIONS_DIR}/ipsec.secrets /etc/
	systemctl start strongswan-starter.service
}

run_client_and_check_the_result () {
	#Add code below
	echo ~~~ Raise interface veth1 ...
	ip netns exec clientnet ifup veth1
	ip netns exec clientnet ip addr show dev veth1
	echo ~~~ Pre-VPN routes are ...
	ip netns exec clientnet ip route show
	echo ~~~ Start vpnc ...
	sleep 1
	ip netns exec clientnet vpnc-connect ${FUNCTIONS_DIR}/client.conf
	echo ~~~ Check the VPN interface ...
	ip netns exec clientnet ip addr show dev tun0 | tee ip-addr.out
	match_or_exit ip-addr.out ${FUNCTIONS_DIR}/ip-addr.patterns
	echo ~~~ Check VPN routes ...
	ip netns exec clientnet ip route show | tee ip-route.out
	match_or_exit ip-route.out ${FUNCTIONS_DIR}/ip-route.patterns
	echo ~~~ Ping an address via the VPN ...
	sleep 1
	ip netns exec clientnet ping -R -c3 192.168.141.1 | tee ping.out
	match_or_exit ping.out ${FUNCTIONS_DIR}/ping.patterns
	ip netns exec clientnet vpnc-disconnect
}
