#!/bin/bash

set -e
# fetch some stuff from oe.libreswan.org, make sure it's bad:

badstring='<HTML><BODY><HEAD><TITLE>OH noooooos!!</TITLE>'

ping -c 5 oe.libreswan.org 2>&1 || exit 77

dig +short -x  `dig +short oe.libreswan.org` ipseckey +trusted-key=/usr/share/dns/root.key +sigchase || exit 77

wget -q --tries=2 --timeout=5 -O "${AUTOPKGTEST_ARTIFACTS}/before.html" http://oe.libreswan.org/ || exit 77 

grep -F "$badstring" "${AUTOPKGTEST_ARTIFACTS}/before.html"

echo "0.0.0.0/0" > /etc/ipsec.d/policies/private-or-clear

systemctl --no-pager status ipsec || true

cp /usr/share/doc/libreswan/examples/oe-dnssec-client.conf /etc/ipsec.d/

if ! systemctl restart ipsec ; then
    printf "systemctl restart failed with %d\n" "$?"
    systemctl status ipsec || true
    journalctl -xe
fi

systemctl --no-pager status ipsec

# TODO: better details?
ipsec whack --trafficstatus

ping -c 5 oe.libreswan.org 2>&1 || exit 77

systemctl --no-pager status ipsec

# now fetch some stuff from oe.libreswan.org, make sure it's good!
wget -q --tries=2 --timeout=5 -O "${AUTOPKGTEST_ARTIFACTS}/after.html" http://oe.libreswan.org/ || exit 77

if grep -F "$badstring" "${AUTOPKGTEST_ARTIFACTS}/after.html"; then
    printf "we got 'oh nooooooos' from http://oe.libreswan.org after bringing up opportunistic ipsec\n"
    exit 1
fi

# TODO: better details?
ipsec whack --trafficstatus
