#!/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
}

# Don't need --no-module-dir or --no-data-dir as they are set as env vars in test_env.sh
COMMON_OPTS="--daemon --config $CONFIG --load-module $SSL_LIB --ssl-cert-db $CERT_DIR --ssl-cert-password-file $CERT_PW_FILE --ssl-cert-name $TEST_HOSTNAME"

# Start new brokers:
#   $1 must be integer
#   $2 = extra opts
# Append used ports to PORTS variable
start_brokers() {
    local -a ports
    for (( i=0; $i<$1; i++)) do
        ports[$i]=$($QPIDD_EXEC --port 0 $COMMON_OPTS $2) || error "Could not start broker $i"
    done
    PORTS=( ${PORTS[@]} ${ports[@]} )
}

# Stop single broker:
#   $1 is number of broker to stop (0 based)
stop_broker() {
    $QPIDD_EXEC -qp ${PORTS[$1]}

    # Remove from ports array
    unset PORTS[$1]
}

stop_brokers() {
    for port in "${PORTS[@]}";
    do
        $QPIDD_EXEC -qp $port
    done
    PORTS=()
}

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
}

cleanup() {
    stop_brokers
    delete_certs
}

start_ssl_broker() {
    start_brokers 1 "--transport ssl --ssl-port 0 --require-encryption --auth no"
}

start_ssl_mux_broker() {
    ../qpidd $COMMON_OPTS --port $1 --ssl-port $1 --auth no
    PORTS=( ${PORTS[@]} $1 )
}

start_authenticating_broker() {
    start_brokers 1 "--transport ssl --ssl-port 0 --require-encryption --ssl-sasl-no-dict --ssl-require-client-authentication --auth yes"
}

ssl_cluster_broker() {		# $1 = port
    start_brokers 1 "--ssl-port $1 --auth no --load-module  $CLUSTER_LIB --cluster-name ssl_test.$HOSTNAME.$$ --cluster-url amqp:ssl:$TEST_HOSTNAME:$1"

    # Wait for broker to be ready
    qpid-ping -Pssl -b $TEST_HOSTNAME -qp $1 || { echo "Cannot connect to broker on $1"; exit 1; }
}

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"

start_ssl_broker
PORT=${PORTS[0]}
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; }

## Test connection with a combination of URL and connection options (in messaging API)
URL=$TEST_HOSTNAME:$PORT
./qpid-send -b $URL --connection-options '{transport:ssl,heartbeat:2}' --content-string='hello again' -a "foo;{create:always}"
MSG=`./qpid-receive -b $URL --connection-options '{transport:ssl,heartbeat:2}' -a "foo;{create:always}" --messages 1`
test "$MSG" = "hello again" || { echo "receive failed '$MSG' != 'hello again'"; exit 1; }

#### Client Authentication tests

start_authenticating_broker
PORT2=${PORTS[1]}
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 ssl muxed with plain TCP on the same connection

# Test a specified port number - since tcp/ssl are the same port don't need to specify --transport ssl
PORT=`pick_port`
start_ssl_mux_broker $PORT || error "Could not start broker"
echo "Running SSL/TCP mux test on fixed port $PORT"

## Test connection via connection settings
./qpid-perftest --count ${COUNT} --port ${PORT} -P ssl -b $TEST_HOSTNAME --summary || error "SSL connection failed!"
./qpid-perftest --count ${COUNT} --port ${PORT} -P tcp -b $TEST_HOSTNAME --summary || error "TCP connection failed!"

# Test a broker chosen port - since ssl chooses port need to use --transport ssl here
start_ssl_broker
PORT=${PORTS[0]}
echo "Running SSL/TCP mux test on random port $PORT"

## Test connection via connection settings
./qpid-perftest --count ${COUNT} --port ${PORT} -P ssl -b $TEST_HOSTNAME --summary || error "SSL connection failed!"
./qpid-perftest --count ${COUNT} --port ${PORT} -P tcp -b $TEST_HOSTNAME --summary || error "TCP connection failed!"

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.

PORT1=`pick_port`; ssl_cluster_broker $PORT1
echo "Running SSL cluster broker on port $PORT1"

PORT2=`pick_port`; ssl_cluster_broker $PORT2
echo "Running SSL cluster broker on port $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}"

stop_broker 0 # Kill broker 1 - receiver should fail-over.
echo "Killed SSL cluster broker on port $PORT1"

./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.*

