#! /bin/bash
set -e

function wait_for_server() {
  until `$JBOSS_HOME/bin/jboss-cli.sh -c ":read-attribute(name=server-state)" 2> /dev/null | grep -q running`; do
    echo "Retry ..."
  done
}

echo "dump environment variables to env.properties file"
printenv > env.properties

echo "starting JBoss"
nohup $JBOSS_HOME/bin/standalone.sh --admin-only 1>&2  2>/dev/null &

# running system patches
wait_for_server
$JBOSS_HOME/bin/jboss-cli.sh --connect --file="./patches/system/init.cli" --properties=env.properties
$JBOSS_HOME/bin/jboss-cli.sh --connect --file="./patches/system/add-postgresql-driver.cli" --properties=env.properties
bash "./patches/system/add-demo-user.sh"

# running project patches
find ./patches/ -type f -name '*.cli' -not -path './patches/system/*' -print0 |
while IFS= read -r -d '' f; do
    wait_for_server
    echo "running $f"
    $JBOSS_HOME/bin/jboss-cli.sh --connect --file="$f" --properties=env.properties
done;

find ./patches/ -type f -name '*.sh' -not -path './patches/system/*' -print0 |
while IFS= read -r -d '' f; do
    wait_for_server
    echo "running $f"
    bash "$f"
done

echo "stopping JBoss"
wait_for_server
$JBOSS_HOME/bin/jboss-cli.sh --connect --command=:shutdown

if ! [[ -z $SERVER_START ]]; then
    echo "starting JBoss in standalone"
    sleep 10 # without this occurs error "address already in use"
    /opt/jboss/wildfly/bin/standalone.sh -c  standalone.xml -b 0.0.0.0 -bmanagement 0.0.0.0
else
    echo "cleaning up JBoss logs"
    rm -rf $JBOSS_HOME/standalone/log
fi
