#!/bin/sh
#
# Pre Startup script for the Casa Authtoken Service Daemon (casa_atsd)
#
# systemd-casa_atsd-prestart
# This runs as root

DAEMON_USER=casaatsd
DAEMON_GROUP=casaauth

. /etc/CASA/authtoken/svc/envvars

    # Try to fix permissions
    chown --dereference $DAEMON_USER:$DAEMON_GROUP "$CATALINA_BASE"
    for dir in "$CATALINA_BASE/conf" \
               "$CATALINA_BASE/logs" \
               "$CATALINA_BASE/temp" \
               "$CATALINA_BASE/webapps" \
               "$CATALINA_BASE/work" ; do
      # the command true is used because of for example conf directory may be mounted read-only
      test -d "$dir" && chown -R --dereference $DAEMON_USER:$DAEMON_GROUP "$dir" 2>/dev/null || true
    done

    TEST_IBM_JVM=$($JAVA_HOME/bin/java -version 2>&1 | grep -i ibm)

    # Make sure that the server.xml link has been made
    if [ ! -f /srv/www/casaats/conf/server.xml ]; then
      # The server.xml file link needs to be made. Use the appropriate
      # file for the JVM version that we are using.
      if [ -z "${TEST_IBM_JVM}" ]; then
        # Assume Sun JVM
        # Use PKCS12 version if PKCS12 store exists
        if [ -f /etc/ssl/servercerts/keystore.p12 ]; then
          ln -s /srv/www/casaats/conf/server-pkcs12-sun.xml /srv/www/casaats/conf/server.xml
        else
          ln -s /srv/www/casaats/conf/server-sun.xml /srv/www/casaats/conf/server.xml
        fi
      else
        # IBM JVM
        # Use PKCS12 version if PKCS12 store exists
        if [ -f /etc/ssl/servercerts/keystore.p12 ]; then
          ln -s /srv/www/casaats/conf/server-pkcs12-ibm.xml /srv/www/casaats/conf/server.xml
        else
          ln -s /srv/www/casaats/conf/server-ibm.xml /srv/www/casaats/conf/server.xml
        fi
      fi

      # Make sure that our service has rights to the file
      chown -h casaatsd:casaauth /srv/www/casaats/conf/server.xml
    fi
