#!/bin/bash

set +e

{
date
whoami
env


# configure CONTEXT_ROOT

mkdir -p $CATALINA_BASE/conf/Catalina/localhost
cp $WEBAPP_DIR/META-INF/context.xml $CATALINA_BASE/conf/Catalina/localhost/$ACCESS_CONTEXT_ROOT.xml


# env SECURITY (deprecated)

case $SECURITY in
   iamtoken)
      echo "SECURITY is set: "$SECURITY
      cd $WEBAPP_DIR/WEB-INF/ && rm -f web.xml && cp web-cutout-$SECURITY.xml web.xml && cd -
      cp /etc/pki/tls/server-connector.xml $CATALINA_BASE/conf
      cp /etc/pki/tls/iamtoken.properties $WEBAPP_DIR/WEB-INF/classes/
      ;;
   *)
      echo "SECURITY not configured."
      ;;
esac


# configure TLS

if [ -f /etc/pki/tls/keystore.jks ] && [ -f /etc/pki/tls/keystore.pwd ];
then
   cp $CATALINA_BASE/conf/server-connector.xml-8443 $CATALINA_BASE/conf/server-connector.xml
fi

case $KEYSTORE_ALIAS in
   *)
      echo "KEYSTORE_ALIAS: "$KEYSTORE_ALIAS
      sed -i "s/tomcat/$KEYSTORE_ALIAS/" $CATALINA_BASE/conf/server-connector.xml
      ;;
esac


# configure SKA IAM

if [ -z "$SKAIAM_INTROSPECT" ] || [ -z "$SKAIAM_CLIENT" ] || [ -z "$SKAIAM_PASSWORD" ];
then
   echo "Some of SKAIAM_ is not set."
   echo "url: "$SKAIAM_INTROSPECT
   echo "cli: "$SKAIAM_CLIENT
   echo "pwd: "$SKAIAM_PASSWORD
else
   echo "Config SKA IAM ..."
   {
      echo "introspect=$SKAIAM_INTROSPECT"
      echo "client_name=$SKAIAM_CLIENT"
      echo "client_password=$SKAIAM_PASSWORD"
   } > $WEBAPP_DIR/WEB-INF/classes/iamtoken.properties
   cp $WEBAPP_DIR/WEB-INF/web-cutout-iamtoken.xml $WEBAPP_DIR/WEB-INF/web.xml
fi


date
} 1> /tmp/start-soda.log 2>&1

$CATALINA_HOME/bin/catalina.sh run

