#!/bin/sh

# Copyright (C) 2017 Nikos Mavrogiannopoulos
#
# Author: Nikos Mavrogiannopoulos
#
# This file is part of GnuTLS.
#
# GnuTLS 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 3 of the License, or (at
# your option) any later version.
#
# GnuTLS 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 Lesser General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>

srcdir="${srcdir:-.}"
SERV="${SERV:-../src/gnutls-serv${EXEEXT}}"
CLI="${CLI:-../src/gnutls-cli${EXEEXT}}"
unset RETCODE
TMPFILE=self-signed.$$.pem.tmp

if ! test -x "${SERV}"; then
	exit 77
fi

if ! test -x "${CLI}"; then
	exit 77
fi

if test "${WINDIR}" != ""; then
	exit 77
fi 

if ! test -z "${VALGRIND}"; then
	VALGRIND="${LIBTOOL:-libtool} --mode=execute ${VALGRIND} --error-exitcode=15"
fi

SERV="${SERV} -q"

. "${srcdir}/scripts/common.sh"

skip_if_no_datefudge

echo "Checking whether connecting to a self signed certificate returns the expected error"

cat <<__EOF__ >${TMPFILE}
-----BEGIN CERTIFICATE-----
[payload removed: 1496 characters in 24 lines]
-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----
[payload removed: 2356 characters in 37 lines]
-----END RSA PRIVATE KEY-----
__EOF__

eval "${GETPORT}"
launch_server $$ --echo --x509keyfile ${TMPFILE} --x509certfile ${TMPFILE}
PID=$!
wait_server ${PID}

datefudge "2018-1-1" \
${VALGRIND} "${CLI}" -p "${PORT}" localhost >${TMPFILE} 2>&1 </dev/null && \
	fail ${PID} "1. handshake should have failed!"


kill ${PID}
wait

grep -E "Status: The certificate is NOT trusted. The certificate issuer is unknown.[[:space:]]*\$" ${TMPFILE}
if ! test $? = 0;then
	echo "Did not find the expected error code"
	grep "Status:" ${TMPFILE}
	exit 1
fi

rm -f ${TMPFILE}

exit 0
