#!/bin/sh
#
# Validate GlobalProtect NLB config parsing against fake-gp-server NLB mode.
PRELOAD=1
srcdir=${srcdir:-.}
top_builddir=${top_builddir:-..}

. `dirname $0`/common.sh

FINGERPRINT="--servercert=pin-sha256:xp3scfzy3rO"
CERT=$certdir/server-cert.pem
KEY=$certdir/server-key.pem

echo "Testing GlobalProtect NLB auth/config against fake server ..."

OCSERV=${srcdir}/fake-gp-server.py
launch_simple_sr_server $ADDRESS 443 $CERT $KEY >/dev/null 2>&1
PID=$!
wait_server $PID

SERVURL="https://$ADDRESS:443"
CLIENT="$OPENCONNECT --protocol=gp $FINGERPRINT -u test"
export LD_PRELOAD=libsocket_wrapper.so

echo "Configuring fake server for NLB gateway getconfig."
curl -sk $SERVURL/CONFIGURE -d nlb=1

echo -n "Authenticating with username/password via portal (NLB mode)... "
( echo "test" | $CLIENT $SERVURL/portal --cookieonly >/dev/null 2>&1) ||
    fail $PID "Could not receive cookie from fake GlobalProtect NLB server"

echo ok

echo -n "Verifying NLB fields are parsed from getconfig.esp... "
LOG="$SOCKDIR/nlb-log.$$.tmp"
( echo "test" | timeout 20 $CLIENT --no-dtls $SERVURL/portal >"$LOG" 2>&1) || true
grep -q 'NLB enabled' "$LOG" ||
    fail $PID "Expected NLB enabled message in openconnect output"

echo ok

echo "Resetting fake server to default configuration."
curl -sk $SERVURL/CONFIGURE -d ''

cleanup

exit 0
