#!/bin/bash
#
# Copyright (C) 2013 Nikos Mavrogiannopoulos
#
# This file is part of ocserv.
#
# ocserv is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# ocserv is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GnuTLS; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

SERV="${SERV:-../src/ocserv}"
srcdir=${srcdir:-.}

. `dirname $0`/common.sh
. `dirname $0`/random-vpnnet.sh
# the per-user network of testipnet in tests/data/user-config
alloc_vpnnet4 VPNUSERNET

eval "${GETPORT}"

echo "Testing ocserv and user route application... "

rm -f test-iroute.tmp

update_config_dir user-config
update_config test-iroute.config
launch_simple_server -d 1 -f -c "${CONFIG}"
PID=$!
wait_server $PID

echo -n "Connecting to obtain cookie (with certificate)... "
( $OPENCONNECT -q localhost:$PORT --sslkey ${srcdir}/certs/user-key.pem -c ${srcdir}/certs/user-cert.pem --servercert=pin-sha256:xp3scfzy3rOQsv9NcOve/8YVVv+pHr4qNCXEXrNl5s8= --cookieonly </dev/null ) ||
	fail $PID "Could not connect with certificate!"

echo ok

echo -n "Re-connecting to force script run... "
$OPENCONNECT -q localhost:$PORT --sslkey ${srcdir}/certs/user-key.pem -c ${srcdir}/certs/user-cert.pem --servercert=pin-sha256:xp3scfzy3rOQsv9NcOve/8YVVv+pHr4qNCXEXrNl5s8= -s /bin/true </dev/null &
kpid=$!
echo ok

sleep 2
kill $kpid

sleep 1
echo -n "Checking if routes have been applied... "

if [ ! -f test-iroute.tmp ];then
	fail $PID "Temporary file cannot be found"
fi

# route-add-cmd records "%R %{RI} %D" for the iroute of user test;
# see REQ-MAIN-NET-005
CONTENTS=`cat test-iroute.tmp`
if ! echo "$CONTENTS" | grep -Eqx '203\.0\.113\.0/255\.255\.255\.0 203\.0\.113\.0/24 (vpns|tun)[0-9]+';then
	fail $PID "FAIL: expected '203.0.113.0/255.255.255.0 203.0.113.0/24 vpns<N>', got '$CONTENTS'"
fi

echo ok

rm -f test-iroute.tmp ${CONFIG}
rm -rf ${CONFIG_PER_USER_DIR}

kill $PID
wait

exit 0
