#!/bin/bash

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

# Run a simple test over SSL
source ./test_env.sh

CONFIG=$(dirname $0)/config.null
CERT_DIR=`pwd`/test_cert_db
CERT_PW_FILE=`pwd`/cert.password
TEST_HOSTNAME=127.0.0.1
TEST_CLIENT_CERT=rumplestiltskin
COUNT=10

trap cleanup EXIT

error() { echo $*; exit 1; }

create_certs() {
    #create certificate and key databases with single, simple, self-signed certificate in it
    mkdir ${CERT_DIR}
    certutil -N -d ${CERT_DIR} -f ${CERT_PW_FILE}
    certutil -S -d ${CERT_DIR} -n ${TEST_HOSTNAME} -s "CN=${TEST_HOSTNAME}" -t "CT,," -x -f ${CERT_PW_FILE} -z /usr/bin/certutil
    certutil -S -d ${CERT_DIR} -n ${TEST_CLIENT_CERT} -s "CN=${TEST_CLIENT_CERT}" -t "CT,," -x -f ${CERT_PW_FILE} -z /usr/bin/certutil
}

delete_certs() {
    if [[ -e ${CERT_DIR} ]] ;  then
        rm -rf ${CERT_DIR}
    fi
}

COMMON_OPTS="--daemon --no-data-dir --no-module-dir --auth no --config $CONFIG --load-module $SSL_LIB --ssl-cert-db $CERT_DIR --ssl-cert-password-file $CERT_PW_FILE --ssl-cert-name $TEST_HOSTNAME --require-encryption"
start_broker() { # $1 = extra opts
    ../qpidd --transport ssl --port 0 --ssl-port 0 $COMMON_OPTS $1;
}

stop_brokers() {
    test -n "$PORT" && ../qpidd --no-module-dir -qp $PORT
    test -n "$PORT2" && ../qpidd --no-module-dir -qp $PORT2
    PORT=""
    PORT2=""
}

cleanup() {
    stop_brokers
    delete_certs
}

CERTUTIL=$(type -p certutil)
if [[ !(-x $CERTUTIL) ]] ; then
    echo "No certutil, skipping ssl test";
    exit 0;
fi

if [[ !(-e ${CERT_PW_FILE}) ]] ;  then
    echo password > ${CERT_PW_FILE}
fi
delete_certs
create_certs || error "Could not create test certificate"
PORT=`start_broker` || error "Could not start broker"
echo "Running SSL test on port $PORT"
export QPID_NO_MODULE_DIR=1
export QPID_LOAD_MODULE=$SSLCONNECTOR_LIB
export QPID_SSL_CERT_DB=${CERT_DIR}
export QPID_SSL_CERT_PASSWORD_FILE=${CERT_PW_FILE}

## Test connection via connection settings
./qpid-perftest --count ${COUNT} --port ${PORT} -P ssl -b $TEST_HOSTNAME --summary

## Test connection with a URL
URL=amqp:ssl:$TEST_HOSTNAME:$PORT
./qpid-send -b $URL --content-string=hello -a "foo;{create:always}"
MSG=`./qpid-receive -b $URL -a "foo;{create:always}" --messages 1`
test "$MSG" = "hello" || { echo "receive failed '$MSG' != 'hello'"; exit 1; }

#### Client Authentication tests

PORT2=`start_broker --ssl-require-client-authentication`  || error "Could not start broker"
echo "Running SSL client authentication test on port $PORT2"
URL=amqp:ssl:$TEST_HOSTNAME:$PORT2

## See if you can set the SSL cert-name for the connection
./qpid-send -b $URL --connection-options "{ssl-cert-name: $TEST_CLIENT_CERT }"  --content-string=hello -a "bar;{create:always}"
MSG2=`./qpid-receive -b $URL  --connection-options "{ssl-cert-name: $TEST_CLIENT_CERT }" -a "bar;{create:always}" --messages 1`
test "$MSG2" = "hello" || { echo "receive failed '$MSG2' != 'hello'"; exit 1; }

## Make sure that connect fails with an invalid SSL cert-name
./qpid-send -b $URL --connection-options "{ssl-cert-name: pignose }" --content-string=hello -a "baz;{create:always}" 2>/dev/null 1>/dev/null
MSG3=`./qpid-receive -b $URL  --connection-options "{ssl-cert-name: pignose }" -a "baz;{create:always}" --messages 1 2>/dev/null`
test "$MSG3" = "" || { echo "receive succeeded without valid ssl cert '$MSG3' != ''"; exit 1; }

stop_brokers

test -z $CLUSTER_LIB && exit 0	# Exit if cluster not supported.

## Test failover in a cluster using SSL only
. $srcdir/ais_check		# Will exit if clustering not enabled.

pick_port() {
    # We need a fixed port to set --cluster-url. Use qpidd to pick a free port.
    PICK=`../qpidd --no-module-dir -dp0`
    ../qpidd --no-module-dir -qp $PICK
    echo $PICK
}
ssl_cluster_broker() {		# $1 = port
    ../qpidd $COMMON_OPTS --load-module  $CLUSTER_LIB --cluster-name ssl_test.$HOSTNAME.$$ --cluster-url amqp:ssl:$TEST_HOSTNAME:$1 --port 0 --ssl-port $1 --transport ssl > /dev/null
    # Wait for broker to be ready
    qpid-ping -Pssl -b $TEST_HOSTNAME -qp $1 || { echo "Cannot connect to broker on $1"; exit 1; }
    echo "Running SSL cluster broker on port $1"
}

PORT1=`pick_port`; ssl_cluster_broker $PORT1
PORT2=`pick_port`; ssl_cluster_broker $PORT2

# Pipe receive output to uniq to remove duplicates
./qpid-receive --connection-options "{reconnect:true, reconnect-timeout:5}" --failover-updates -b amqp:ssl:$TEST_HOSTNAME:$PORT1 -a "foo;{create:always}" -f | uniq > ssl_test_receive.tmp &
./qpid-send -b amqp:ssl:$TEST_HOSTNAME:$PORT2 --content-string=one -a "foo;{create:always}"
../qpidd --no-module-dir -qp $PORT1 # Kill broker 1 receiver should fail-over.
./qpid-send -b amqp:ssl:$TEST_HOSTNAME:$PORT2 --content-string=two -a "foo;{create:always}" --send-eos 1
wait				# Wait for qpid-receive
{ echo one; echo two; } > ssl_test_receive.cmp
diff  ssl_test_receive.tmp ssl_test_receive.cmp || { echo "Failover failed"; exit 1; }
rm -f ssl_test_receive.*

