#!/bin/bash

# Terminate configure if no JBoss AS7 (kszkipo-as7) installed in system
array=($(rpmquery -a | grep kszkipo-as7))
if [[ ${#array[@]} == 0 ]]; then
    echo "JBoss AS7 (kszkipo-as7) not installed!"
    exit 0
fi

. ../contrib/config
. ../contrib/functions.sh

# Default server hosts
#JBOSS_PRIMARY_HOST=172.16.0.104
#JBOSS_STANDBY_HOST=172.16.0.204
#PGPOOL_DELEGATE_IP=172.16.0.155

echo -n "JBOSS PRIMARY HOST (Default: $JBOSS_PRIMARY_HOST): "
read _JBOSS_PRIMARY_HOST
if [[ ! -z $_JBOSS_PRIMARY_HOST ]]; then
    JBOSS_PRIMARY_HOST=$_JBOSS_PRIMARY_HOST
fi

echo -n "JBOSS STANDBY HOST (Default: $JBOSS_STANDBY_HOST): "
read _JBOSS_STANDBY_HOST
if [[ ! -z $_JBOSS_STANDBY_HOST ]]; then
    JBOSS_STANDBY_HOST=$_JBOSS_STANDBY_HOST
fi
echo -n "PostgreSQL host (Default: $PGPOOL_DELEGATE_IP): "
read _PGPOOL_DELEGATE_IP
if [[ ! -z $_PGPOOL_DELEGATE_IP ]]; then
    PGPOOL_DELEGATE_IP=$_PGPOOL_DELEGATE_IP
fi


sysctl -w net.core.rmem_max=50000000 &>/dev/null
sysctl -w net.core.wmem_max=640000 &>/dev/null

if ! grep -Fq "net.core.rmem_max" /etc/sysctl.conf; then
    echo "net.core.rmem_max = 50000000" >> /etc/sysctl.conf
fi
if ! grep -Fq "net.core.wmem_max" /etc/sysctl.conf; then
    echo "net.core.wmem_max = 640000" >> /etc/sysctl.conf
fi

# Memory configure for applications JVM
# This params as example for 8 cores and 8 Gb server
SERVER_HEAP_SIZE="1g"
SERVER_MAX_HEAP_SIZE="4g"
SERVER_PERMGEN_SIZE="1g"
SERVER_MAX_PERMGEN_SIZE="4g"
# Memory for process and host controller JVM
# This params as example for 8 cores and 8 Gb server
HOST_HEAP_SIZE="256m"
HOST_MAX_HEAP_SIZE="1024m"
HOST_PERMGEN_SIZE="1024m"
HOST_MAX_PERMGEN_SIZE="1024m"

# standby user password on primary server
STANDBY_BASE64=c3RhbmRieSExMjM0NQ\=\=

DS_POOL_NAMES=()
DS_JNDI_NAMES=()
DS_CONNECTION_URLS=()
# Database users
DS_USERS=()
# Original passwords which will be encrypted. Not uses in generate domain.xml datasources
DS_PASSWORDS=()

function add_ds() {
    if [[ $# != 5 ]]; then
        echo "Wrong function parameters count!"
        exit 1
    fi

    DS_POOL_NAMES+=($1)
    DS_JNDI_NAMES+=($2)
    DS_CONNECTION_URLS+=($3)
    DS_USERS+=($4)
    DS_PASSWORDS+=($5)
}
#         POOL NAME                JNDI NAME                                CONNECTION                                   LOGIN      PASS
add_ds "otd414_ds_irz_1" "java:jboss/datasources/otd414_ds_irz_1" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz_uch" "postgres" "postgres"
add_ds "otd414_ds_irz_2" "java:jboss/datasources/otd414_ds_irz_2" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "otd414_ds_geobase_v6" "java:jboss/datasources/otd414_ds_geobase_v6" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/geobase_v6" "postgres" "postgres"
add_ds "java:/jdbc/irz/NA" "java:/jdbc/irz/NA" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "user0" "aaaaaaaa"
add_ds "java:/jdbc/irz/RW" "java:/jdbc/irz/RW" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "user1" "aaaaaaaa"
add_ds "java:/jdbc/irz/RO" "java:/jdbc/irz/RO" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "user2" "aaaaaaaa"
add_ds "java:/jdbc/irz_uch/NA" "java:/jdbc/irz_uch/NA" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz_uch" "user0" "aaaaaaaa"
add_ds "java:/jdbc/irz_uch/RW" "java:/jdbc/irz_uch/RW" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz_uch" "user1" "aaaaaaaa"
add_ds "java:/jdbc/irz_uch/RO" "java:/jdbc/irz_uch/RO" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz_uch" "user2" "aaaaaaaa"
add_ds "irz" "java:/irz" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "irz_uch" "java:/irz_uch" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz_uch" "postgres" "postgres"
add_ds "RosjankaDbScenarioDataDatasource" "java:jboss/datasources/RosjankaDbScenarioDataDatasource" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "RosjankaExportReportsDatasource" "java:jboss/datasources/RosjankaExportReportsDatasource" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "RosjankaDbLogDatasource" "java:jboss/datasources/RosjankaDbLogDatasource" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "RosjankaIndicatorMainDataDatasource" "java:jboss/datasources/RosjankaIndicatorMainDataDatasource" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "RosjankaIndicatorClassificatorDataDatasource" "java:jboss/datasources/RosjankaIndicatorClassificatorDataDatasource" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"
add_ds "DozerDatasource" "java:jboss/datasources/DozerDatasource" "jdbc:postgresql://$PGPOOL_DELEGATE_IP:5432/irz" "postgres" "postgres"

usage="$(basename "$0") [-h] [-p] [-s] [-d] -- Script configure JBoss AS 7.2.0 Final domain cluster mode
where:
    -h  show this help text and exit
    -p  configure JBoss as primary server
    -s  configure JBoss as standby server
    -d  recursive deploy apps from war folder"

while getopts ':psdvh' option; do
    case "$option" in
        p) TYPE=primary
            ;;
        s) TYPE=standby
            ;;
        v) VERBOSE=true
            ;;
        d) DEPLOY=true
            ;;
        h) echo "$usage"
            exit
            ;;
        \?) printf "illegal option: -%s\n" "$OPTARG" >&2
            echo "$usage" >&2
            exit 1
            ;;
    esac
done


if [[ -z $TYPE ]]; then
    TYPE=primary
fi

if [[ "$TYPE" == "primary" ]]; then
    HOST=$JBOSS_PRIMARY_HOST
fi
if [[ "$TYPE" == "standby" ]]; then
    HOST=$JBOSS_STANDBY_HOST
fi

export JBOSS_HOME=/opt/kszkipo/as7
export PATH=${JBOSS_HOME}/bin:${PATH}

# For easy access later
ln -sf ${JBOSS_HOME}"/bin/jboss-cli.sh" ${JBOSS_HOME}"/bin/jboss-cli"
# Install my tools
cp -rf bin/dodeploy* /usr/local/bin/

ENCRYPT_CLASS_PATH=${JBOSS_HOME}"/modules/system/layers/base/org/picketbox/main/*"
ENCRYPT_CLASS_PATH=${ENCRYPT_CLASS_PATH}:"${JBOSS_DIR}/modules/system/layers/base/org/jboss/logging/main/*"

if ! grep -Fq "JBOSS_DC_MODE" /etc/kszkipo/as7/jboss-as.conf; then
    echo -e "#--backup - on standby server will be backup domain controll data\n#--cached-dc - use backuped domain controll data on standby if primary is fail" >> /etc/kszkipo/as7/jboss-as.conf
    if [[ "$TYPE" == "primary" ]]; then
        echo "JBOSS_DC_MODE=" >> /etc/kszkipo/as7/jboss-as.conf
    fi
    if [[ "$TYPE" == "standby" ]]; then
        echo "JBOSS_DC_MODE=--backup" >> /etc/kszkipo/as7/jboss-as.conf
    fi
fi

if ! grep -Fq "JBOSS_DC_MODE" /etc/init.d/as7-domain; then
    sed -i "s/--host-config=\$JBOSS_HOST_CONFIG/--host-config=\$JBOSS_HOST_CONFIG \$JBOSS_DC_MODE/g" /etc/init.d/as7-domain
fi

JBOSS_PROFILE=/etc/profile.d/jboss.sh
if [[ ! -f $JBOSS_PROFILE ]]; then
    echo 'export JBOSS_HOME='${JBOSS_HOME}'
export PATH=${JBOSS_HOME}/bin:${PATH}' >> /etc/profile.d/jboss.sh
fi

cp domain/*.xml /etc/kszkipo/as7/domain

# Install thirdparty modules
cp -rf modules/* ${JBOSS_HOME}/modules/system/layers/base/
chown as7 ${JBOSS_HOME} -R

# Turn on domain mode for as7
chkconfig as7-standalone off
chkconfig as7-domain on
service as7-domain restart

# Switch main-server-group to full-ha profile
# Remove all profiles
align_left "$DOTSTRING" "Removing server groups"
result=`jboss-cli.sh --connect --commands="batch,
/server-group=main-server-group:remove(),
/server-group=other-server-group:remove(),
run-batch"` &>/dev/null
align_echo $? $result $result
# Remove full-sockets, ha-sockets, standard-sockets
#/socket-binding-group=standard-sockets:remove(),
align_left "$DOTSTRING" "Remove full and ha sockets"
result=`jboss-cli.sh --connect --commands="batch,
/socket-binding-group=full-sockets:remove(),
/socket-binding-group=ha-sockets:remove(),
run-batch"` &>/dev/null
align_echo $? $result $result
# First create standalone server group. Use it for non clustered application. Only one instace will be worked.
# If failover event, on standalone server must start on standby
align_left "$DOTSTRING" "Create standalone-server-group"
result=`jboss-cli.sh --connect --commands="/server-group=standalone-server-group:add(profile=default, socket-binding-group=standard-sockets)"` &>/dev/null
align_echo $? $result
# Configure main-server-group jvm options
align_left "$DOTSTRING" "Configure standalone-server-group"
result=`jboss-cli.sh --connect --commands="batch,
/server-group=standalone-server-group/jvm=default:add(heap-size=$SERVER_HEAP_SIZE, max-heap-size=$SERVER_MAX_HEAP_SIZE, permgen-size=$SERVER_PERMGEN_SIZE, max-permgen-size=$SERVER_MAX_PERMGEN_SIZE),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-XX:+UseParallelGC\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dsun.rmi.dgc.client.gcInterval=1800000\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dsun.rmi.dgc.server.gcInterval=1800000\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-XX:ParallelGCThreads=8\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dorg.geotools.coverage.jaiext.enabled=true\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Djava.library.path=/usr/local/GISCore/lib/:/usr/lib/jni/\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Ddozer.cfg=/etc/kszkipo/as7/standalone/_cfg_dozer\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dindicators_vso.cfg=/etc/irz/indicators_vso\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dindicators_p.cfg=/etc/irz/indicators_p\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dplanning.cfg=/etc/irz/planning\"),
/server-group=standalone-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dfile.encoding=UTF-8\"),
run-batch"` &>/dev/null
align_echo $? $result

# Create correct main-server-group
align_left "$DOTSTRING" "Create cluster-server-group"
result=`jboss-cli.sh --connect --commands="/server-group=cluster-server-group:add(profile=full-ha, socket-binding-group=full-ha-sockets)"` &>/dev/null
align_echo $? $result
# Configure main-server-group jvm options
align_left "$DOTSTRING" "Configure cluster-server-group"
reuslt=`jboss-cli.sh --connect --commands="batch,
/server-group=cluster-server-group/jvm=default:add(heap-size=$SERVER_HEAP_SIZE, max-heap-size=$SERVER_MAX_HEAP_SIZE, permgen-size=$SERVER_PERMGEN_SIZE, max-permgen-size=$SERVER_MAX_PERMGEN_SIZE),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-XX:+UseParallelGC\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dsun.rmi.dgc.client.gcInterval=1800000\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dsun.rmi.dgc.server.gcInterval=1800000\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-XX:ParallelGCThreads=8\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dorg.geotools.coverage.jaiext.enabled=true\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Djava.library.path=/usr/local/GISCore/lib/:/usr/lib/jni/\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Ddozer.cfg=/etc/kszkipo/as7/standalone/_cfg_dozer\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dindicators_vso.cfg=/etc/irz/indicators_vso\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dindicators_p.cfg=/etc/irz/indicators_p\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dplanning.cfg=/etc/irz/planning\"),
/server-group=cluster-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dfile.encoding=UTF-8\"),
run-batch"` &>/dev/null
align_echo $? $result

# Remove default profile
function remove_default_profile {
jboss-cli.sh --connect --commands="batch,
    /profile=default/subsystem=weld:remove(),
    /profile=default/subsystem=webservices:remove(),
    /profile=default/subsystem=threads:remove(),
    /profile=default/subsystem=sar:remove(),
    /profile=default/subsystem=resource-adapters:remove(),
    /profile=default/subsystem=remoting:remove(),
    /profile=default/subsystem=pojo:remove(),
    /profile=default/subsystem=naming:remove(),
    /profile=default/subsystem=mail:remove(),
    /profile=default/subsystem=jsf:remove(),
    /profile=default/subsystem=jmx:remove(),
    /profile=default/subsystem=jdr:remove(),
    /profile=default/subsystem=jca:remove(),
    /profile=default/subsystem=jpa:remove(),
    /profile=default/subsystem=jaxrs:remove(),
    /profile=default/subsystem=infinispan:remove(),
    /profile=default/subsystem=ejb3:remove(),
    /profile=default/subsystem=datasources:remove(),
    /profile=default/subsystem=configadmin:remove(),
    /profile=default/subsystem=logging:remove(),
    /profile=default/subsystem=transactions:remove(),
    /profile=default/subsystem=web:remove(),
    /profile=default/subsystem=ee:remove(),
    /profile=default/subsystem=security:remove(),
    /profile=default:remove(),
    run-batch"
}

# Remove ha profile
function remove_ha_profile {
    # Bug in JBoss AS7, cant remove ha profile, because can't remove jgroups subsystem
    sed -i '/<subsystem xmlns="urn:jboss:domain:jgroups:1.1" default-stack="udp">/,/<\/subsystem>/{x;/./{x;b};x;/<\/subsystem>/h;d}' /etc/kszkipo/as7/domain/domain.xml
    service as7-domain restart
    jboss-cli.sh --connect --commands="batch,
        /profile=ha/subsystem=weld:remove(),
        /profile=ha/subsystem=webservices:remove(),
        /profile=ha/subsystem=threads:remove(),
        /profile=ha/subsystem=sar:remove(),
        /profile=ha/subsystem=resource-adapters:remove(),
        /profile=ha/subsystem=remoting:remove(),
        /profile=ha/subsystem=pojo:remove(),
        /profile=ha/subsystem=naming:remove(),
        /profile=ha/subsystem=mail:remove(),
        /profile=ha/subsystem=jsf:remove(),
        /profile=ha/subsystem=jmx:remove(),
        /profile=ha/subsystem=jdr:remove(),
        /profile=ha/subsystem=jca:remove(),
        /profile=ha/subsystem=jpa:remove(),
        /profile=ha/subsystem=jaxrs:remove(),
        /profile=ha/subsystem=infinispan:remove(),
        /profile=ha/subsystem=ejb3:remove(),
        /profile=ha/subsystem=datasources:remove(),
        /profile=ha/subsystem=configadmin:remove(),
        /profile=ha/subsystem=logging:remove(),
        /profile=ha/subsystem=transactions:remove(),
        /profile=ha/subsystem=web:remove(),
        /profile=ha/subsystem=ee:remove(),
        /profile=ha/subsystem=security:remove(),
        /profile=ha/subsystem=modcluster:remove(),
        /profile=ha:remove(),
        run-batch"
}

# Remove full profile
function remove_full_profile {
    jboss-cli.sh --connect --commands="batch,
        /profile=full/subsystem=cmp:remove(),
        /profile=full/subsystem=configadmin:remove(),
        /profile=full/subsystem=datasources:remove(),
        /profile=full/subsystem=ee:remove(),
        /profile=full/subsystem=ejb3:remove(),
        /profile=full/subsystem=infinispan:remove(),
        /profile=full/subsystem=jacorb:remove(),
        /profile=full/subsystem=jaxr:remove(),
        /profile=full/subsystem=jaxrs:remove(),
        /profile=full/subsystem=jca:remove(),
        /profile=full/subsystem=jdr:remove(),
        /profile=full/subsystem=jmx:remove(),
        /profile=full/subsystem=jpa:remove(),
        /profile=full/subsystem=jsf:remove(),
        /profile=full/subsystem=jsr77:remove(),
        /profile=full/subsystem=logging:remove(),
        /profile=full/subsystem=mail:remove(),
        /profile=full/subsystem=messaging:remove(),
        /profile=full/subsystem=naming:remove(),
        /profile=full/subsystem=pojo:remove(),
        /profile=full/subsystem=remoting:remove(),
        /profile=full/subsystem=resource-adapters:remove(),
        /profile=full/subsystem=sar:remove(),
        /profile=full/subsystem=security:remove(),
        /profile=full/subsystem=threads:remove(),
        /profile=full/subsystem=transactions:remove(),
        /profile=full/subsystem=web:remove(),
        /profile=full/subsystem=webservices:remove(),
        /profile=full/subsystem=weld:remove(),
        /profile=full:remove(),
        run-batch"
}

#remove_default_profile
#remove_ha_profile
#remove_full_profile

# Third party configs
align_left "$DOTSTRING" "Configure thirdparty settings for defalt profile"
result=`jboss-cli.sh --connect --commands="/profile=default/subsystem=naming/binding=java\:global\/journal_settings:add(binding-type=object-factory,module=org.otdel414.commons,class=org.otdel414.journal.JournalSettings\$Factory,environment=[szi=\"enable:true\", out=\"enable:true,params:false,only_error:true\"])"` &>/dev/null
align_echo $? $result
align_left "$DOTSTRING" "Configure thirdparty settings for full-ha profile"
result=`jboss-cli.sh --connect --commands="/profile=full-ha/subsystem=naming/binding=java\:global\/journal_settings:add(binding-type=object-factory,module=org.otdel414.commons,class=org.otdel414.journal.JournalSettings\$Factory,environment=[szi=\"enable:true\", out=\"enable:true,params:false,only_error:true\"])"` &>/dev/null
align_echo $? $result

# Set max post size request
align_left "$DOTSTRING" "Configure max-post-size for default profile"
result=`jboss-cli.sh --connect --commands="/profile=default/subsystem=web/connector=http:write-attribute(name=max-post-size,value=0)"` &>/dev/null
align_echo $? $result
align_left "$DOTSTRING" "Configure max-post-size for full-ha profile"
result=`jboss-cli.sh --connect --commands="/profile=full-ha/subsystem=web/connector=http:write-attribute(name=max-post-size,value=0)"` &>/dev/null
align_echo $? $result

# Set transcations tumeout
align_left "$DOTSTRING" "Configure default-timeout for default profile"
result=`jboss-cli.sh --connect --commands="/profile=default/subsystem=transactions:write-attribute(name=default-timeout,value=300000)"` &>/dev/null
align_echo $? $result
align_left "$DOTSTRING" "Configure default-timeout for default profile"
result=`jboss-cli.sh --connect --commands="/profile=full-ha/subsystem=transactions:write-attribute(name=default-timeout,value=300000)"` &>/dev/null
align_echo $? $result

# Set user and password for HornetQ server
align_left "$DOTSTRING" "Configure HornetQ server"
result=`jboss-cli.sh --connect --commands="batch,
/profile=full-ha/subsystem=messaging/hornetq-server=default:write-attribute(name=cluster-user, value=jms-user),
/profile=full-ha/subsystem=messaging/hornetq-server=default:write-attribute(name=cluster-password, value=jms-pass),
run-batch"` &>/dev/null
align_echo $? $result

# Set instance-id for domain:web
align_left "$DOTSTRING" "Configure instance-id HornetQ server"
reuslt=`jboss-cli.sh --connect --commands='/profile=full-ha/subsystem=web:write-attribute(name=instance-id, value=\"${jboss.node.name}\")'` &>/dev/null
align_echo $? $result

# Rename master -> primary
align_left "$DOTSTRING" "Rename server master -> primary"
result=`jboss-cli.sh --connect --commands="/host=master:write-attribute(name=name, value=$TYPE)"` &>/dev/null
align_echo $? $result

# Configure interfaces
align_left "$DOTSTRING" "Configure interfaces"
result=`jboss-cli.sh --connect --commands="batch,
/host=master/interface=management:write-attribute(name=inet-address, value=$HOST),
/host=master/interface=public:write-attribute(name=inet-address, value=0.0.0.0),
/host=master/interface=unsecure:write-attribute(name=inet-address, value=0.0.0.0),
run-batch"` &>/dev/null
align_echo $? $result

if [[ "$TYPE" == "standby" ]]; then
    # Disable local domain controller, attach to primary
    align_left "$DOTSTRING" "Disable local domanin controller"
    result=`jboss-cli.sh --connect --commands="/host=master:write-remote-domain-controller(host=$JBOSS_PRIMARY_HOST, port=9999, security-realm=ManagementRealm)"` &>/dev/null
    align_echo $? $result
    # Set secret value for standby user
    align_left "$DOTSTRING" "Configure ManagementRealm"
    result=`jboss-cli.sh --connect --commands="/host=master/core-service=management/security-realm=ManagementRealm/server-identity=secret:add(value=\"$STANDBY_BASE64\")"` &>/dev/null
    align_echo $? $result
fi

# Create standalone server
align_left "$DOTSTRING" "Create server-standalone"
result=`jboss-cli.sh --connect --commands="/host=master/server-config=server-standalone:add(group=standalone-server-group, auto-start=false)"` &>/dev/null
align_echo $? $result

# Recreate server-one
align_left "$DOTSTRING" "Stop server-one"
result=`jboss-cli.sh --connect --commands="/host=master/server-config=server-one:stop()"` &>/dev/null
align_echo $? $result
align_left "$DOTSTRING" "Recreate server-one"
result=`jboss-cli.sh --connect --commands="batch,
/host=master/server-config=server-one:remove(),
/host=master/server-config=server-one:add(group=cluster-server-group, socket-binding-port-offset=150, auto-start=true),
run-batch"` &>/dev/null
align_echo $? $result
# Recreate server two
align_left "$DOTSTRING" "Stop server-two"
result=`jboss-cli.sh --connect --commands="/host=master/server-config=server-two:stop()"` &>/dev/null
align_echo $? $result
align_left "$DOTSTRING" "Recreate server-two"
result=`jboss-cli.sh --connect --commands="batch,
/host=master/server-config=server-two:remove(),
/host=master/server-config=server-two:add(group=cluster-server-group, socket-binding-port-offset=300, auto-start=true),
run-batch"` &>/dev/null
align_echo $? $result
# Remove server-three
align_left "$DOTSTRING" "Remove server-three"
result=`jboss-cli.sh --connect --commands="/host=master/server-config=server-three:remove()"` &>/dev/null
align_echo $? $result

# Set controllers memory usage
align_left "$DOTSTRING" "Reconfigure controllers"
result=`jboss-cli.sh --connect --commands="batch,
/host=master/jvm=default:remove(),
/host=master/jvm=default:add(heap-size=$HOST_HEAP_SIZE, max-heap-size=$HOST_MAX_HEAP_SIZE, permgen-size=$HOST_PERMGEN_SIZE, max-permgen-size=$HOST_MAX_PERMGEN_SIZE),
/host=master/jvm=default:add-jvm-option(jvm-option="\""-server"\""),
run-batch"` &>/dev/null
align_echo $? $result
#jboss-cli.sh --connect --commands="/host=master/jvm=default:add-jvm-option(jvm-option="\""-Djgroups.bind_addr=$HOST"\"")"

# Configure system properties for servers
align_left "$DOTSTRING" "Configure system properties"
result=`jboss-cli.sh --connect --commands="batch,
/host=master/server-config=server-one/system-property=jgroups.bind_addr:add(value=$HOST),
/host=master/server-config=server-two/system-property=jgroups.bind_addr:add(value=$HOST),
/host=master/server-config=server-one/system-property=GEOSERVER_DATA_DIR:add(value=/data/geoserver-data/server-one),
/host=master/server-config=server-two/system-property=GEOSERVER_DATA_DIR:add(value=/data/geoserver-data/server-two),
run-batch"` &>/dev/null
align_echo $? $result

# Configure admin password and standby password
add-user.sh -u admin -p admin\!12345 -s &>/dev/null
add-user.sh -u standby -p standby\!12345 -s &>/dev/null

# Add PostgreSQL JDBC driver
align_left "$DOTSTRING" "Add PostgreSQL JDBC Driver"
result=`jboss-cli.sh --connect --commands="batch,
/profile=default/subsystem=datasources/jdbc-driver=postgresql:add(driver-name=postgresql, driver-module-name=org.postgresql, driver-xa-datasource-class-name=org.postgresql.xa.PGXADataSource),
/profile=full-ha/subsystem=datasources/jdbc-driver=postgresql:add(driver-name=postgresql, driver-module-name=org.postgresql, driver-xa-datasource-class-name=org.postgresql.xa.PGXADataSource),
run-batch"` &>/dev/null
align_echo $? $result

# Remove ExampleDS datasource
align_left "$DOTSTRING" "Remove ExampleDS datasource"
result=`jboss-cli.sh --connect --commands="batch,
/profile=default/subsystem=datasources/data-source=ExampleDS:remove(),
/profile=full-ha/subsystem=datasources/data-source=ExampleDS:remove(),
run-batch"` &>/dev/null
align_echo $? $result

echo "Begin configure encrypted password's"
for ((i = 0; i < ${#DS_POOL_NAMES[@]}; i++)); do
    # Encript passwords for datasources
    encrypted=`java -classpath ${ENCRYPT_CLASS_PATH} org.picketbox.datasource.security.SecureIdentityLoginModule "${DS_PASSWORDS[$i]}"`
    encrypted=(${encrypted// / });
    encrypted=${encrypted[2]}
    align_left "$DOTSTRING" "${DS_USERS[$i]}"
    result=`jboss-cli.sh --connect --commands="batch,
        /profile=default/subsystem=security/security-domain=encrypted_pass_$i:add(cache-type=default),
        /profile=default/subsystem=security/security-domain=encrypted_pass_$i/authentication=classic:add(),
        /profile=default/subsystem=security/security-domain=encrypted_pass_$i/authentication=classic/login-module=postgres_login_module:add(code=SecureIdentity, flag=required,module-options=[username="${DS_USERS[$i]}", password="$encrypted"]),
        /profile=full-ha/subsystem=security/security-domain=encrypted_pass_$i:add(cache-type=default),
        /profile=full-ha/subsystem=security/security-domain=encrypted_pass_$i/authentication=classic:add(),
        /profile=full-ha/subsystem=security/security-domain=encrypted_pass_$i/authentication=classic/login-module=postgres_login_module:add(code=SecureIdentity, flag=required,module-options=[username="${DS_USERS[$i]}", password="$encrypted"]),
        run-batch"` &>/dev/null
    align_echo $? $result
done

echo "Begin configure DataSource's"
for ((i = 0; i < ${#DS_POOL_NAMES[@]}; i++)); do
    # Add datasources from matrix
    min_pool_size=1
    max_pool_size=25
    align_left "$DOTSTRING" "${DS_POOL_NAMES[$i]}"
    result=`jboss-cli.sh --connect --commands="batch,
    /profile=default/subsystem=datasources/data-source=\"${DS_POOL_NAMES[$i]}\":add(
        jndi-name=\"${DS_JNDI_NAMES[$i]}\",
        connection-url=\"${DS_CONNECTION_URLS[$i]}\",
        driver-class=org.postgresql.Driver,
        driver-name=postgresql,
        min-pool-size=$min_pool_size,
        max-pool-size=$max_pool_size,
        enabled=true,
        use-java-context=true,
        security-domain=encrypted_pass_$i,
        pool-prefill=false,
        pool-use-strict-min=true,
        allow-multiple-users=true,
        check-valid-connection-sql=\"SELECT 1\",
        validate-on-match=true,
        background-validation-millis=1,
        background-validation=true
        ),
    /profile=full-ha/subsystem=datasources/data-source=\"${DS_POOL_NAMES[$i]}\":add(
        jndi-name=\"${DS_JNDI_NAMES[$i]}\",
        connection-url=\"${DS_CONNECTION_URLS[$i]}\",
        driver-class=org.postgresql.Driver,
        driver-name=postgresql,
        min-pool-size=$min_pool_size,
        max-pool-size=$max_pool_size,
        enabled=true,
        use-java-context=true,
        security-domain=encrypted_pass_$i,
        pool-prefill=false,
        pool-use-strict-min=true,
        allow-multiple-users=true,
        check-valid-connection-sql=\"SELECT 1\",
        validate-on-match=true,
        background-validation-millis=1,
        background-validation=true
        ),
    run-batch"` &>/dev/null
    align_echo $? $result
done

# Set properties for load-demo application, use for debug
align_left "$DOTSTRING" "Configure global system-properties"
result=`jboss-cli.sh --connect --commands="batch,
    /system-property=org.apache.tomcat.util.ENABLE_MODELER:add(value=true),
    /system-property=org.apache.coyote.http11.Http11Protocol.COMPRESSION:add(value=on),
    /system-property=org.apache.coyote.http11.Http11Protocol.COMPRESSION_MIME_TYPES:add(value=\"text/javascript,text/css,text/html\"),
    /system-property=org.apache.catalina.connector.URI_ENCODING:add(value=UTF-8),
    /system-property=org.apache.catalina.connector.USE_BODY_ENCODING_FOR_QUERY_STRING:add(value=true),
    /system-property=org.otd414.security.null_user_restrict:add(value=false),
    /system-property=org.otd414.security.dont_create_views:add(value=false),
    /system-property=org.otd414.servername:add(value=jboss.7.2),
    run-batch"` &>/dev/null
align_echo $? $result

service as7-domain restart

if [[ "$TYPE" == "primary" ]]; then
    if [[ $DEPLOY == true ]]; then
        dodeploy-cluster war/
    fi
fi
