#!/bin/bash



source "/etc/openshift/node.conf"

# Creates a jboss instance
# Variables used in this script:
: << --COMMENT--
# jboss.version
jboss_home = the location where the jboss server is installed
jboss_version = the name/type of the jboss cartridge, e.g., jbossas-7, jbosseap-6.0
# /etc/openshift/node.conf
CREATE_APP_SYMLINK = Enable user-unobfuscate to create ~/appname-namespace in addition to ~/uuid
GEAR_BASE_DIR=Users home dirs (where customer data ends up)
# Script arguments
namespace=basename $2
application=$1
uuid=$3
git_url=$4


# Script local
JBOSS_CARTRIDGE_ROOT=${CARTRIDGE_BASE_PATH}/${jboss_version}
APP_HOME = ${GEAR_BASE_DIR}/${uuid} # the root directory for application contents
GIT_DIR = $APP_HOME/git/$application.git
M2_DIR = $APP_HOME/.m2 # maven dir
APP_JBOSS = $JBOSS_INSTANCE_DIR/${jboss_version} # the application jboss root
APP_JBOSS_BIN_DIR = $JBOSS_INSTANCE_DIR/${jboss_version}/bin
APP_JBOSS_TMP_DIR = $JBOSS_INSTANCE_DIR/${jboss_version}/standalone/tmp # application jboss tmp dir
--COMMENT--

# Exit on any errors
set -e

# Load the jboss_version and jboss_home settings
. `dirname $0`/jboss.version

function print_help {
    echo "Usage: $0 app-name namespace uuid"

    echo "$0 $@" | logger -p local0.notice -t openshift_origin_jboss_configure
    exit 1
}

function create_repo {
    application="$1"
    user_id=$2
    group_id=$3
    uuid=$4

    if [ ! -d $APP_HOME ]; then echo "ERROR: Application ${uuid} not found!  Please create." 1>&2; exit 2; fi

    GIT_DIR=$APP_HOME/git/$application.git
    mkdir -p "$APP_HOME/git"
    
    cp -ad ${CARTRIDGE_BASE_PATH}/${jboss_version}/template $APP_HOME/git
    
    pushd $APP_HOME/git/template > /dev/null
    sed -i "s/{APP_NAME}/$application/g" pom.xml
    mkdir -p .openshift/config
    cp "$APP_JBOSS"/standalone/configuration/standalone.xml .openshift/config
    chmod -R 0644 .openshift/config
    cat <<__EOF__ > .gitignore
target
__EOF__
    git init > /dev/null
    git add .openshift .gitignore *
    git commit -m 'Creating template' > /dev/null
    popd > /dev/null
    pushd $APP_HOME/git > /dev/null
    git clone --bare --no-hardlinks template $application.git > /dev/null
    rm -rf template
    popd > /dev/null
    
    setup_git_repo $application $user_id $group_id $uuid $jboss_version
}

function create_jboss_network_env_vars {
  CART_NS=$(get_cartridge_namespace_from_path)

  echo "export OPENSHIFT_${CART_NS}_CLUSTER_PORT='7600'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_CLUSTER_PORT
  echo "export OPENSHIFT_${CART_NS}_CLUSTER='$IP[7600]'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_CLUSTER
  echo "export OPENSHIFT_${CART_NS}_CLUSTER_PROXY_PORT='7600'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_CLUSTER_PROXY_PORT
  echo "export OPENSHIFT_${CART_NS}_CLUSTER_REMOTING='$IP:4447'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_CLUSTER_REMOTING
  echo "export OPENSHIFT_${CART_NS}_REMOTING_PORT='4447'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_REMOTING_PORT
  echo "export OPENSHIFT_${CART_NS}_MESSAGING_PORT='5445'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_MESSAGING_PORT
  echo "export OPENSHIFT_${CART_NS}_MESSAGING_THROUGHPUT_PORT='5455'" > $APP_HOME/.env/OPENSHIFT_${CART_NS}_MESSAGING_THROUGHPUT_PORT
}

while getopts 'd' OPTION
do
    case $OPTION in
        d) set -x
        ;;
        ?) print_help
        ;;
    esac
done

[ $# -eq 4 -o $# -eq 3 ] || print_help

JBOSS_CARTRIDGE_ROOT=$CARTRIDGE_BASE_PATH/${jboss_version}
cartridge_type="${jboss_version}"

source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util
setup_configure "$1" $2 $3 $4

disable_cgroups
check_cartridge_dir_doesnt_exist

# The root of the application jboss contents
JBOSS_INSTANCE_DIR=$(get_cartridge_instance_dir "$jboss_version")
APP_JBOSS=$JBOSS_INSTANCE_DIR/${jboss_version}
# Maven dir
M2_DIR=`echo $APP_HOME/.m2 | tr -s /`
mkdir -p $M2_DIR
JAVA_PREFS_DIR=`echo $APP_HOME/.java | tr -s /`
mkdir -p $JAVA_PREFS_DIR

APP_JBOSS_TMP_DIR="$APP_JBOSS"/standalone/tmp
mkdir -p ${APP_JBOSS_TMP_DIR}


#
# Find an open localhost IP
#
IP=`find_open_ip $uid $uuid`

#
# Create jboss base for application, every app gets its own jboss instance
#
create_cartridge_instance_dir "$cartridge_type"
pushd "$JBOSS_INSTANCE_DIR" > /dev/null
create_standard_app_dirs
mkdir -p ${jboss_version}/{bin,standalone/configuration}
# application jboss bin directory
APP_JBOSS_BIN_DIR="$APP_JBOSS"/bin

cd ${jboss_version}
# Create a link to the jboss server modules jar and modules directory
ln -s ${jboss_home}/jboss-modules.jar
ln -s ${jboss_home}/modules

# Copy the jboss server install standalone configuration files
cp ${jboss_home}/standalone/configuration/{standalone.xml,*.properties} "$APP_JBOSS"/standalone/configuration
# Look for cartridge overrides of the configuration/{standalone.xml,logging.properties}

cp ${JBOSS_CARTRIDGE_ROOT}/info/configuration/standalone.xml "$APP_JBOSS"/standalone/configuration
cp ${JBOSS_CARTRIDGE_ROOT}/info/configuration/logging.properties "$APP_JBOSS"/standalone/configuration

# Link to the standalone.sh script
ln -s ${JBOSS_CARTRIDGE_ROOT}/info/bin/standalone.sh $APP_JBOSS_BIN_DIR/standalone.sh

# Link to the standalone.conf file
ln -s ${JBOSS_CARTRIDGE_ROOT}/info/bin/standalone.conf $APP_JBOSS_BIN_DIR/standalone.conf

popd > /dev/null

# Repo
if [ ! -d $git_url ]; then
	clone_external_git_repo $application $user_id $group_id $uuid $git_url
else
	create_repo $application $user_id $group_id $uuid
fi

# Create a link from the repo/deployments directory to the standalone/deployments content
mkdir -p "$APP_REPO_DIR"/deployments
ln -s "$APP_REPO_DIR"/deployments "$APP_JBOSS"/standalone/deployments

# Create a link from the standalone/log directory to ${APP_DIR}/logs for rhc app tail
ln -s ${jboss_version}/standalone/log "$JBOSS_INSTANCE_DIR"/logs

# Run any specific configuration steps needed by the concrete cart. For now this is
# pretty specific and hard coded at this stage in the flow. If requirements expand,
# a stronger API could be established in order to allow extensions at other points
# in the configure execuction.
concrete_configure="${JBOSS_CARTRIDGE_ROOT}/info/hooks/configure-${cartridge_type}"
echo "checking for concrete configure script at ${concrete_configure}"
if [ -f $concrete_configure ]; then
    echo "executing concrete configure script ${concrete_configure}"
    $concrete_configure $JBOSS_CARTRIDGE_ROOT $APP_JBOSS
fi

populate_repo_dir

# Copy the example WAR to the deployments directories
cp ${JBOSS_CARTRIDGE_ROOT}/info/data/ROOT.war $APP_REPO_DIR/deployments

chmod +x "$APP_JBOSS_BIN_DIR/standalone.sh" || error "Failed to chmod new application scripts" 122
secure_app_dir
secure_cart_instance_dir
# Secure script and config dirs.
chown $user_id.$group_id -R "$JBOSS_INSTANCE_DIR/${jboss_version}/standalone"
chown -R $user_id.$group_id $M2_DIR
observe_setup_app_and_git_dirs
observe_setup_cart_instance_dir
chown -R $user_id.$group_id $JAVA_PREFS_DIR

#
# Create environment variables
#
export CART_INFO_DIR=$JBOSS_CARTRIDGE_ROOT/info

create_standard_cart_env_vars
create_standard_env_uservars
create_standard_network_env_vars $IP
create_cart_network_env_vars $IP
create_jboss_network_env_vars
create_standard_repo_dir_env_var
create_standard_path_env_var

# source the new PATH so we can modify it
. $APP_HOME/.env/PATH

if [ -e $APP_HOME/app-root/runtime/repo/.openshift/markers/java7 ];
then
	JAVA_HOME=/etc/alternatives/java_sdk_1.7.0
else
	JAVA_HOME=/etc/alternatives/java_sdk_1.6.0
fi
M2_HOME=/etc/alternatives/maven-3.0
echo "export JAVA_HOME=$JAVA_HOME" > $APP_HOME/.env/JAVA_HOME
echo "export M2_HOME=$M2_HOME" > $APP_HOME/.env/M2_HOME
echo "export PATH=$JAVA_HOME/bin:$M2_HOME/bin:$PATH" > $APP_HOME/.env/PATH

observe_setup_env_uservars_dir

if [ ! -d $git_url ]; then
    #
    # Resolve app dependencies for template
    #
    resolve_application_dependencies $uuid $application &
else
    #
    # Start the server
    #
    cd $JBOSS_INSTANCE_DIR
    start_app
fi

#
# Create virtualhost definition for apache
#

$JBOSS_CARTRIDGE_ROOT/info/bin/deploy_httpd_proxy.sh $application $namespace $uuid $IP

enable_cgroups
