#!/bin/bash

# Default server hosts
PRIMARY_HOST=172.16.0.104
STANDBY_HOST=172.16.0.204

SERVER_HEAP_SIZE="2g"
SERVER_MAX_HEAP_SIZE="4g"
SERVER_PERMGEN_SIZE="512m"
SERVER_MAX_PERMGEN_SIZE="4g"

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\=\=

# Matrix of datasources
DS_POOL_NAMES=(
    "otd414_ds_irz_1"
    "otd414_ds_irz_2"
    "otd414_ds_geobase"
    "java:/jdbc/irz/NA"
    "java:/jdbc/irz/RW"
    "java:/jdbc/irz/RO"
    "java:/jdbc/irz_uch/NA"
    "java:/jdbc/irz_uch/RW"
    "java:/jdbc/irz_uch/RO"
    "irz"
    "irz_uch"
);
DS_JNDI_NAMES=(
    "java:jboss/datasources/otd414_ds_irz_1"
    "java:jboss/datasources/otd414_ds_irz_2"
    "java:jboss/datasources/otd414_ds_geobase_v6"
    "java:/jdbc/irz/NA"
    "java:/jdbc/irz/RW"
    "java:/jdbc/irz/RO"
    "java:/jdbc/irz_uch/NA"
    "java:/jdbc/irz_uch/RW"
    "java:/jdbc/irz_uch/RO"
    "java:/irz"
    "java:/irz_uch"
);
DS_CONNECTION_URLS=(
    "jdbc:postgresql://172.16.0.155:5432/irz_uch"
    "jdbc:postgresql://172.16.0.155:5432/irz"
    "jdbc:postgresql://172.16.0.155:5432/geobase_v6"
    "jdbc:postgresql://172.16.0.155:5432/irz"
    "jdbc:postgresql://172.16.0.155:5432/irz"
    "jdbc:postgresql://172.16.0.155:5432/irz"
    "jdbc:postgresql://172.16.0.155:5432/irz_uch"
    "jdbc:postgresql://172.16.0.155:5432/irz_uch"
    "jdbc:postgresql://172.16.0.155:5432/irz_uch"
    "jdbc:postgresql://172.16.0.155:5432/irz"
    "jdbc:postgresql://172.16.0.155:5432/irz_uch"
);
# Database users
DS_USERS=(
    "postgres"
    "postgres"
    "postgres"
    "user0"
    "user1"
    "user2"
    "user0"
    "user1"
    "user2"
    "postgres"
    "postgres"
);
# Original passwords which will be encrypted. Not uses in generate domain.xml datasources
DS_PASSWORDS=(
    "postgres"
    "postgres"
    "postgres"
    "aaaaaaaa"
    "aaaaaaaa"
    "aaaaaaaa"
    "aaaaaaaa"
    "aaaaaaaa"
    "aaaaaaaa"
    "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=$PRIMARY_HOST
fi
if [[ "$TYPE" == "standby" ]]; then
    HOST=$STANDBY_HOST
fi

# 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

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

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
jboss-cli.sh --connect --commands="batch,
/server-group=main-server-group:remove(),
/server-group=other-server-group:remove(),
run-batch"
# Remove full-sockets, ha-sockets, standard-sockets
jboss-cli.sh --connect --commands="batch,
/socket-binding-group=standard-sockets:remove(),
/socket-binding-group=full-sockets:remove(),
/socket-binding-group=ha-sockets:remove(),
run-batch"
# Create correct main-server-group
jboss-cli.sh --connect --commands="/server-group=main-server-group:add(profile=full-ha, socket-binding-group=full-ha-sockets)"
# Configure main-server-group jvm options
jboss-cli.sh --connect --commands="batch,
/server-group=main-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=main-server-group/jvm=default:add-jvm-option(jvm-option=\"-XX:+UseParallelGC\"),
/server-group=main-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dsun.rmi.dgc.client.gcInterval=1800000\"),
/server-group=main-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dsun.rmi.dgc.server.gcInterval=1800000\"),
/server-group=main-server-group/jvm=default:add-jvm-option(jvm-option=\"-XX:ParallelGCThreads=8\"),
/server-group=main-server-group/jvm=default:add-jvm-option(jvm-option=\"-Dorg.geotools.coverage.jaiext.enabled=true\"),
/server-group=main-server-group/jvm=default:add-jvm-option(jvm-option=\"-Djava.library.path=/usr/local/GISCore/lib/:/usr/lib/jni/\"),
run-batch"

# 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
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\"])"

# Set max post size request
jboss-cli.sh --connect --commands="/profile=full-ha/subsystem=web/connector=http:write-attribute(name=max-post-size,value=0)"

# Set transcations tumeout
jboss-cli.sh --connect --commands="/profile=full-ha/subsystem=transactions:write-attribute(name=default-timeout,value=300000)"

# Set user and password for HornetQ server
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"

# Set instance-id for domain:web
jboss-cli.sh --connect --commands='/profile=full-ha/subsystem=web:write-attribute(name=instance-id, value=\"${jboss.node.name}\")'

# Rename master -> primary
jboss-cli.sh --connect --commands="/host=master:write-attribute(name=name, value=$TYPE)"

# Configure interfaces
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=$HOST),
/host=master/interface=unsecure:write-attribute(name=inet-address, value=$HOST),
run-batch"

if [[ "$TYPE" == "standby" ]]; then
    # Disable local domain controller, attach to primary
    jboss-cli.sh --connect --commands="/host=master:write-remote-domain-controller(host=$PRIMARY_HOST, port=9999, security-realm=ManagementRealm)"
    # Set secret value for standby user
    jboss-cli.sh --connect --commands="/host=master/core-service=management/security-realm=ManagementRealm/server-identity=secret:add(value=\"$STANDBY_BASE64\")"
fi

# Remove server-three
jboss-cli.sh --connect --commands="/host=master/server-config=server-three:remove()"

# Set controllers memory usage
jboss-cli.sh --connect --commands="/host=master/jvm=default:remove()"
jboss-cli.sh --connect --commands="/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)"
jboss-cli.sh --connect --commands="/host=master/jvm=default:add-jvm-option(jvm-option="\""-server"\"")"

# Configure admin password and standby password
add-user.sh -u admin -p admin\!12345 -s
add-user.sh -u standby -p standby\!12345 -s

# Add PostgreSQL JDBC driver
jboss-cli.sh --connect --commands="/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)"

# Remove ExampleDS datasource
jboss-cli.sh --connect --commands="/profile=full-ha/subsystem=datasources/data-source=ExampleDS:remove()"
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]}
    jboss-cli.sh --connect --commands="batch,
        /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"

    # Add datasources from matrix
    min_pool_size=1
    max_pool_size=50
    jboss-cli.sh --connect --commands="/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
        )"
done

# Set properties for load-demo application, use for debug
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"

if [[ "$TYPE" == "primary" ]]; then
    if [[ $DEPLOY == true ]]; then
        echo "Deploy applications from war folder"
        files=`find war/ -type f`
        files=(${files// / });
        for (( i=0; i < ${#files[@]}; i++ )); do
            # Try assign on all server groups
            result=`jboss-cli.sh --connect --commands="deploy ${files[$i]} --all-server-groups" 2>&1`
            exit_code=$?
            if [[ $exit_code != 0 ]]; then
                # Try update repository
                jboss-cli.sh --connect --commands="deploy ${files[$i]} --force"
                exit_code=$?
                if [[ $exit_code != 0 ]]; then
                    echo -e "${files[$i]}\t\t\t[fail]"
                else
                    echo -e "${files[$i]}\t\t\t[done]"
                fi
            else
                echo -e "${files[$i]}\t\t\t[done]"
            fi
        done
    fi
fi

service as7-domain restart
