#!/usr/bin/env bash

set -x
set -e

########## validate parameter
function validate {
    name=${1}
    value=${2}
    if [ "${value}x" == "x" ] ; then
        echo "[ERROR]: ${name} environment property has not been provided!"
        exit 1
    else
        if [ "${name}" != "AWS_SECRET_ACCESS_KEY" ] ; then
            echo "${name}=${value}"
        fi
    fi
}

##########  backup file
function backup () {
   local src="${1}"
   local dst="${src%.*}-orig.${src##*.}"
   [ -f "${dst}" ] || cp "${src}" "${dst}"
}

########## installs the AWS cli v2
function installAwsCli() {
    aws --version && return || echo "[INFO] Installing aws cli ..."
    export AWS_ACCESS_KEY_ID
    export AWS_SECRET_ACCESS_KEY
    pushd ~
    curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
    unzip awscliv2.zip
    ./aws/install
    popd
}

########## create S3 ping bucket
function createS3Bucket() {
    aws s3api head-bucket --bucket $S3_PING_BUCKET && return || echo "[INFO] Creating S3 Bucket ${S3_PING_BUCKET} ..."
    aws s3api create-bucket --bucket $S3_PING_BUCKET --acl private --region $AWS_DEFAULT_REGION
}

########## delete S3 ping bucket
function deleteS3Bucket() {
    aws s3api head-bucket --bucket $S3_PING_BUCKET || return
    echo "[INFO] Delete AWS S3 bucket $S3_PING_BUCKET"
    aws s3api delete-bucket --bucket $S3_PING_BUCKET --region $AWS_DEFAULT_REGION
}

# S3 bucket for clustering
export AWS_DEFAULT_REGION="us-east-1"
export S3_PING_BUCKET="s3-ping-bucket-as-testsuite"

# Set the location of JBoss EAP inside AWS AMI
export JBOSS_HOME=/opt/rh/eap7/root/usr/share/wildfly

# AWS credentials
validate AWS_ACCESS_KEY_ID ${AWS_ACCESS_KEY_ID}
validate AWS_SECRET_ACCESS_KEY ${AWS_SECRET_ACCESS_KEY}

# mandatory parameters
validate EAP_TAG ${EAP_TAG}

# node type: node with testsuite / node with jboss-eap
validate NODE_TYPE ${NODE_TYPE}


# ===================================================================
# make ssh connection stable
# ===================================================================
sed -i 's/.*ClientAliveInterval.*/ClientAliveInterval 30/' /etc/ssh/sshd_config
systemctl restart sshd

# ===================================================================
# configure current node and run TS on node type AS
# ===================================================================
if [ "${NODE_TYPE}" == "TS" ] ; then

  echo '====================================================='
  echo "[INFO] Initializing Test Suite node"
  echo '====================================================='

  # s3 bucket containing server and maven repos
  validate S3_BITS_BUCKET ${S3_BITS_BUCKET}

  rm -rfd jboss-eap-7.4* eap-local-maven-repository

  # install utilities
  yum install unzip -y

  # install aws cli
  installAwsCli

  # s3 bucket
  createS3Bucket
  trap deleteS3Bucket EXIT

  # working dir
  cd /tmp

  # testsuite sources
  aws s3 cp s3://${S3_BITS_BUCKET}/${EAP_TAG}/jboss-eap-${EAP_TAG}-src.zip /tmp/jboss-eap-${EAP_TAG}-src.zip
  unzip jboss-eap-${EAP_TAG}-src.zip
  rm -f jboss-eap-${EAP_TAG}-src.zip
  export EAP_TS_SOURCES=/tmp/jboss-eap-7.4-src

  # testsuite maven repo
  aws s3 cp s3://${S3_BITS_BUCKET}/${EAP_TAG}/jboss-eap-${EAP_TAG}-testsuite-maven-repository.zip /tmp/jboss-eap-${EAP_TAG}-testsuite-maven-repository.zip
  unzip jboss-eap-${EAP_TAG}-testsuite-maven-repository.zip
  rm -f jboss-eap-${EAP_TAG}-testsuite-maven-repository.zip
  export EAP_TS_LOCAL_MAVEN_REPO=/tmp/eap-local-maven-repository

  # maven repo (needed as well)
  aws s3 cp s3://${S3_BITS_BUCKET}/${EAP_TAG}/jboss-eap-${EAP_TAG}-maven-repository.zip /tmp/jboss-eap-${EAP_TAG}-maven-repository.zip
  unzip jboss-eap-${EAP_TAG}-maven-repository.zip
  rm -f jboss-eap-${EAP_TAG}-maven-repository.zip
  /bin/cp -fr jboss-eap-${EAP_TAG}.GA-maven-repository/maven-repository/* $EAP_TS_LOCAL_MAVEN_REPO

  # eap distribution shipper with the aws ami
  export EAP_DIST_DIR=/tmp/jboss-eap-${EAP_TAG}
  cp -rL ${JBOSS_HOME} ${EAP_DIST_DIR}
  export EAP_CONF_DIR=${EAP_DIST_DIR}/standalone/configuration
  backup ${EAP_CONF_DIR}/standalone-ha.xml
  backup ${EAP_CONF_DIR}/standalone-full-ha.xml
  /bin/cp -f ${EAP_DIST_DIR}/docs/examples/configs/standalone-ec2-ha.xml ${EAP_CONF_DIR}/standalone-ha.xml
  /bin/cp -f ${EAP_DIST_DIR}/docs/examples/configs/standalone-ec2-full-ha.xml ${EAP_CONF_DIR}/standalone-full-ha.xml
  /bin/cp -f ${EAP_DIST_DIR}/docs/examples/configs/domain-ec2.xml ${EAP_CONF_DIR}/domain-ec2.xml
  export EC2_AS_OPTS="${EC2_AS_OPTS} -Djboss.jgroups.s3_ping.access_key=${AWS_ACCESS_KEY_ID}"
  export EC2_AS_OPTS="${EC2_AS_OPTS} -Djboss.jgroups.s3_ping.secret_access_key=${AWS_SECRET_ACCESS_KEY}"
  export EC2_AS_OPTS="${EC2_AS_OPTS} -Djboss.jgroups.s3_ping.bucket=${S3_PING_BUCKET}"

  # run TS
  cd $EAP_TS_SOURCES
  EXIT_STATUS=0
  ./build.sh install \
      -DskipTests \
      -Dmaven.repo.local="${EAP_TS_LOCAL_MAVEN_REPO}" \
      -Denforcer.skip=true
  ./integration-tests.sh install -Dts.iiop -Dts.noSmoke \
      -Denforcer.skip=true \
      -Dmaven.repo.local="${EAP_TS_LOCAL_MAVEN_REPO}" \
      -Djboss.dist="${EAP_DIST_DIR}" \
      -Djvm.args.other="${EC2_AS_OPTS}" \
      -Drem.jboss.server.config.file=standalone-ec2-ha.xml  || EXIT_STATUS=${?}

elif [ "${NODE_TYPE}" == "EAP" ] ; then

  echo '====================================================='
  echo "[INFO] Initializing JBoss EAP node"
  echo '====================================================='

  validate EAP_NODE_NAME ${EAP_NODE_NAME}
  validate INTERNAL_IP_ADDRESS ${INTERNAL_IP_ADDRESS}
  validate EXTERNAL_IP_ADDRESS ${EXTERNAL_IP_ADDRESS}

  # install utilities
  yum install unzip -y

  # install aws cli
  installAwsCli

  # s3 bucket
  createS3Bucket

  # eap profile used to start the node
  export EAP_PROFILE=standalone-ec2-full-ha.xml
  # Set the location of JBoss EAP log files inside AWS AMI
  export JBOSS_LOG_DIR=/var/opt/rh/eap7/log/wildfly/standalone

  # Set the location of the standalone.conf file and set the command used to start EAP in standalone mode
  SERVICE_CONF_FILE=/etc/opt/rh/eap7/wildfly/eap7-standalone.conf

  # Configure JBoss EAP to use the ec2-ha profile
  cp $JBOSS_HOME/docs/examples/configs/$EAP_PROFILE $JBOSS_HOME/standalone/configuration/$EAP_PROFILE
  chown jboss $JBOSS_HOME/standalone/configuration/$EAP_PROFILE
  chgrp jboss $JBOSS_HOME/standalone/configuration/$EAP_PROFILE
  chmod --reference=$JBOSS_HOME/standalone/configuration/standalone.xml $JBOSS_HOME/standalone/configuration/$EAP_PROFILE
  echo "WILDFLY_SERVER_CONFIG=$EAP_PROFILE" >> $SERVICE_CONF_FILE
  echo "WILDFLY_BIND=$INTERNAL_IP_ADDRESS" >> $SERVICE_CONF_FILE
  echo "JAVA_OPTS=\"\$JAVA_OPTS -Djboss.bind.address.external=$EXTERNAL_IP_ADDRESS -Djboss.jgroups.s3_ping.access_key='$AWS_ACCESS_KEY_ID' -Djboss.jgroups.s3_ping.secret_access_key='$AWS_SECRET_ACCESS_KEY' -Djboss.jgroups.s3_ping.bucket='$S3_PING_BUCKET' -Djboss.jvmRoute=$EAP_NODE_NAME -Djboss.bind.address=$INTERNAL_IP_ADDRESS -Djboss.bind.address.private=$INTERNAL_IP_ADDRESS -Djboss.bind.address.management=$INTERNAL_IP_ADDRESS\"" >> $JBOSS_HOME/bin/standalone.conf
  echo "" >> $JBOSS_HOME/bin/standalone.conf

  JBOSS_CLI_SCRIPT=jboss.cli

  cat <<EOT >> /tmp/$JBOSS_CLI_SCRIPT
embed-server --server-config=${EAP_PROFILE}

# set jgroups stack to tcp
/subsystem=jgroups/channel=ee:write-attribute(name=stack,value=tcp)

# node name for clustering
/subsystem=undertow:write-attribute(name=instance-id, value="\${jboss.jvmRoute}")

# change default cluster password
/subsystem=messaging-activemq/server=default:write-attribute(name=cluster-user,value=admin)
/subsystem=messaging-activemq/server=default:write-attribute(name=cluster-password,value=pippobaudo2)
EOT

  # ========================================================
  # run cli script
  # ========================================================
  cat /tmp/$JBOSS_CLI_SCRIPT
  chown -R jboss /tmp/$JBOSS_CLI_SCRIPT
  chgrp -R jboss /tmp/$JBOSS_CLI_SCRIPT
  sudo -g jboss -u jboss $JBOSS_HOME/bin/jboss-cli.sh --file=/tmp/$JBOSS_CLI_SCRIPT

  # add users to jboss eap
  sudo -g jboss -u jboss $JBOSS_HOME/bin/add-user.sh --user admin --password admin

  systemctl enable eap7-standalone
  systemctl start eap7-standalone

  EAP_LOG_MESSAGE="Admin console listening on"
  # wait for the server to start ...
  for i in {1..300}
  do
     sleep 1
     tail -50 $JBOSS_LOG_DIR/server.log | grep "$EAP_LOG_MESSAGE" && break
  done

else
  echo "[ERROR]: Invalid NODE_TYPE=${NODE_TYPE}!"
  exit 1
fi