#!/bin/bash
# Variables that are used to configure the smartexecutor instance
# The HOST variable is not mandatory. The machine FQDN will be used instead
export LOCATION=pisa
export COUNTRY=IT
export INFRA_NAME="gcube"
export SMARTGEARS_SCOPES="/gcube /gcube/devsec /gcube/devNext"
export SMARTGEARS_TOKEN='token'
export AUTHORIZE_CHILDREN='true'

# This script is installed into the VM instance
PATH="/bin:/sbin:/usr/bin:/usr/sbin:$PATH"
HOSTS_FILE=/etc/hosts
PUBLIC_IP=$( wget http://ipecho.net/plain -qO - )
MAIN_IP=$( ip addr show scope global dev eth0 | grep inet | awk '{ print $2 }' | cut -d "/" -f 1 )
TMP_FQDN_HOST=$( host $PUBLIC_IP )
RET_FQDN=$?
if [ $RET_FQDN -eq 0 ] ; then
    PUB_FQDN_HOST=$( host $PUBLIC_IP | awk '{print $5}' | sed -e 's/\.$//g' )
    HOST=$( echo ${PUB_FQDN_HOST} | cut -d . -f 1 - )
    hostname $HOST
    echo "$HOST" > /etc/hostname
    WPS_CONFIG=/home/gcube/tomcat/webapps/wps/config/wps_config.xml
    sed -Ei "s#hostname=\".*\"\ hostport#hostname=\"${PUB_FQDN_HOST}\" hostport#" $WPS_CONFIG
else
   echo "No reverse resolution available. This WPS installation is not going to work"
fi

/usr/local/bin/smartgears-setup

grep -v $PUBLIC_IP $HOSTS_FILE > $HOSTS_FILE.tmp
echo "$PUBLIC_IP $PUB_FQDN_HOST $HOST" >> $HOSTS_FILE.tmp
mv $HOSTS_FILE.tmp $HOSTS_FILE
#
service tomcat-instance-9000 stop
chmod 755 /home/gcube
rm -fr /home/gcube/tomcat/webapps/whn-manager
grep -v authorizeChildrenContext /home/gcube/SmartGears/container.xml > /tmp/container1.xml
grep -v \<\/container\> /tmp/container1.xml > /tmp/container2.xml
echo "<authorizeChildrenContext>true</authorizeChildrenContext>" >> /tmp/container2.xml
echo "</container>" >> /tmp/container2.xml
mv /tmp/container2.xml /home/gcube/SmartGears/container.xml
chown gcube:gcube /home/gcube/SmartGears/container.xml
service tomcat-instance-9000 start
exit 0
