#!/bin/bash

# Prepare env
rm -fr ./standalone/log/server.log
rm -fr ./standalone/configuration/keystore.jks

keytool -genkeypair -alias localhost -keyalg RSA -keysize 1024 -validity 365 -keystore standalone/configuration/keystore.jks -dname "CN=localhost" -keypass secret -storepass secret

# Start iterations to reproduce the issue
iteration=1
found="false"
while test "${found}" = "false"; do
    echo "ITERATION: ${iteration}"
    echo "---------------------------------------------------------------------------------------------------------------------------"
    ./bin/standalone.sh &
    RUNNING_PID=$!
    sleep 5
    ./bin/jboss-cli.sh -c "/subsystem=elytron/server-ssl-context=newServerSSLContext:remove()"
    ./bin/jboss-cli.sh -c "/subsystem=elytron/key-manager=newKeyManager:remove()"
    ./bin/jboss-cli.sh -c "/subsystem=elytron/key-store=newKeyStore:remove()"
    #./bin/jboss-cli.sh -c "reload"
    sleep 1

    echo "killing: ${RUNNING_PID}"
    kill ${RUNNING_PID}
    ps_id=$(ps -aux | grep "java -D\[Standalone\] -server" | tr --squeeze-repeats " " | cut -d " " -f 2)
    echo "killing: ${ps_id}"
    kill ${ps_id}

    ./bin/standalone.sh &
    RUNNING_PID=$!
    sleep 5

    ./bin/jboss-cli.sh -c "/subsystem=elytron/key-store=newKeyStore:add(path=keystore.jks,relative-to=jboss.server.config.dir,credential-reference={clear-text=secret},type=JKS)"
    ./bin/jboss-cli.sh -c "/subsystem=elytron/key-manager=newKeyManager:add(key-store=newKeyStore,algorithm=\"PKIX\",credential-reference={clear-text=secret})"
    ./bin/jboss-cli.sh -c "/subsystem=elytron/server-ssl-context=newServerSSLContext:add(key-manager=newKeyManager,protocols=[\"TLSv1.2\"])"
    sleep 1

    #./bin/jboss-cli.sh -c "shutdown"
    echo "killing: ${RUNNING_PID}"
    kill ${RUNNING_PID}
    ps_id=$(ps -aux | grep "java -D\[Standalone\] -server" | tr --squeeze-repeats " " | cut -d " " -f 2)
    echo "killing: ${ps_id}"
    kill ${ps_id}

    sleep 2
    if grep "MSC000004: Failure during stop of service" ./standalone/log/server.log; then
	 found="true"
    fi
    iteration=$((iteration+1))
done
