#!/bin/bash

set +e
LOG_FILE=/tmp/entrypoint.log

{
date
whoami
env

#########################################################################
echo "run-time config (compose.yaml):"
echo "SECURITY   : "$SECURITY
echo "DISCOVERY_CONTEXT_ROOT : "$DISCOVERY_CONTEXT_ROOT
echo "DB_*                   : "$DB_URI" ["$DB_SCHEMA"] "$DB_USERNAME" / "$DB_PASSWORD
echo "METADATA_PATHNAME  : "$METADATA_PATHNAME
echo "CUTOUT_SERVICE_URL : "$CUTOUT_SERVICE_URL
echo "MERGE_SERVICE_URL  : "$MERGE_SERVICE_URL
echo "RESPONSE_FORMAT    : "$RESPONSE_FORMAT

echo "build-time config'd (Dockefile):"
echo "WEBAPP_DIR : "$WEBAPP_DIR
echo "JAVA_HOME  : "$JAVA_HOME
echo "CATALINA_BASE   : "$CATALINA_BASE
echo "CATALINA_HOME   : "$CATALINA_HOME
echo "CATALINA_TMPDIR : "$CATALINA_TMPDIR
#########################################################################

echo "<Context docBase=\"$WEBAPP_DIR\"/>" > $CATALINA_BASE/conf/Catalina/localhost/$DISCOVERY_CONTEXT_ROOT.xml


# configure DB with ObsCore

{
   echo "db_uri=$DB_URI"
   echo "db_schema=$DB_SCHEMA"
   echo "db_user_name=$DB_USERNAME"
   echo "db_password=$DB_PASSWORD"  
} >> $WEBAPP_DIR/WEB-INF/classes/search.properties


# configure response format

grep db_ $WEBAPP_DIR/WEB-INF/classes/search.properties > $WEBAPP_DIR/WEB-INF/classes/formatresponsefilter.properties
{
   echo "surveys_metadata_abs_pathname=$METADATA_PATHNAME"
   echo "cutout_url=$CUTOUT_SERVICE_URL"
   echo "merge_url=$MERGE_SERVICE_URL"
   if test -n "$RESPONSE_FORMAT"
   then
      echo "response_format=$RESPONSE_FORMAT"
   fi
} >> $WEBAPP_DIR/WEB-INF/classes/formatresponsefilter.properties


# configure security

case $SECURITY in
   ia2token)
      cd $WEBAPP_DIR/WEB-INF/ && rm -f web.xml && cp web-cutout-$SECURITY.xml web.xml && cd -
      cp /etc/pki/tls/server-connector.xml /etc/tomcat9/
      cp /etc/pki/tls/auth*.properties $WEBAPP_DIR/WEB-INF/classes/
      rm -f $WEBAPP_DIR/WEB-INF/lib/jjwt-*0.12*.jar
      ;;  
   iamtoken)
      cd $WEBAPP_DIR/WEB-INF/ && rm -f web.xml && cp web-cutout-$SECURITY.xml web.xml && cd -
      cp /etc/pki/tls/server-connector.xml /etc/tomcat9/
      cp /etc/pki/tls/iamtoken.properties $WEBAPP_DIR/WEB-INF/classes/
      rm -f $WEBAPP_DIR/WEB-INF/lib/jjwt-*0.11*.jar
      ;;  
   *)  
      echo "Security not configured, runs open."
      ;;  
esac


###################################################################
date

} 1> $LOG_FILE 2>&1

/usr/libexec/tomcat9/tomcat-start.sh &

wait -n

