#!/bin/sh
#
# Startup script for the Casa Authtoken Service Daemon (casa_atsd)
#
# /etc/init.d/casa_atsd
#
# description: casa_atsd is the CASA Authentication Token Service
# (ATS). CASA Client utilize this service to obtain CASA authentication
# tokens to authenticate to other services. The ATS executes as a
# tomcat webapp. casa_atsd is the tomcat process which contains
# the ATS.
#
# Note that some of the content from this file was copied from
# /etc/init.d/tomcat5 whose author was Petr Mladek.
# /etc/init.d/tomcat5 has the following copyrights:
#
# Copyright (c) 1995-2001 SuSE GmbH Nuernberg, Germany.
# Copyright (c) 2002 SuSE Linux AG Nuernberg, Germany.
#
# processname: casa_atsd
# pidfile: None
# config utility: None


### BEGIN INIT INFO
# Provides: casa_atsd
# Required-Start: $local_fs $remote_fs
# X-UnitedLinux-Should-Start: $named $syslog $time
# Required-Stop: $local_fs $remote_fs $network
# X-UnitedLinux-Should-Stop: $named $syslog $time
# Default-Start: 2 3 5
# Default-Stop:
# Short-Description: Casa Authtoken Service Daemon
# Description: Start Casa Authtoken Service Daemon
### END INIT INFO

if [ -f /etc/SuSE-release ] ; then
. /etc/rc.status

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
else
  _rc_status=0
  _rc_todo=$1

  function rc_failed() { _rc_status=$1 ; }

  function rc_status()
  {
    if test "$_rc_todo" = "status" ; then
      case "$_rc_status" in
      0) echo "   [ running ]" ;;
      1|2) echo "   [ dead ]" ;;
      3) echo "   [ not running ]" ;;
      *) echo "   [ unknown ]" ;;
      esac
    else
      case "$_rc_status" in
      0) echo "   [ done ]" ;;
      *) echo "   [ failed ]" ;;
      esac
    fi
  }

  function rc_reset() { _rc_status=0 ; }

  function rc_exit() { exit $_rc_status ; }
fi

# First reset status of this service
rc_reset

DAEMON_USER=casaatsd
DAEMON_GROUP=casaauth

atsIsRunning()
{
  ats_ps_log=`mktemp /var/tmp/ats-ps.log.XXXXXX`
  ps aux --cols 1024 >"$ats_ps_log"
  ats_is_running="false"
  if grep " -Dcatalina.base=$CATALINA_BASE.*-Dcatalina.home=$CATALINA_HOME.*org.apache.catalina.startup.Bootstrap" "$ats_ps_log" >/dev/null 2>/dev/null ; then
    ats_is_running="true"
  fi
  rm -f "$ats_ps_log"
  test "$ats_is_running" = "true"
}

StartDAEMON()
{
  # Start the daemon
  echo -n "Starting casa_atsd..."
  ## Start daemon with startproc(8). If this fails
  ## the echo return value is set appropriate.
    
  # NOTE: startproc return 0, even if service is 
  # already running to match LSB spec.
  if atsIsRunning ; then
    rc_failed 0
  else
    # 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)

    # Append the java.security.auth.login.conf property on the JAVA_OPTS environment
    # variable if not utilizing the IBM JVM.
    if [ -z "${TEST_IBM_JVM}" ]; then
      export JAVA_OPTS="$JAVA_OPTS -Djava.security.auth.login.config=/etc/CASA/authtoken/svc/jaas.conf"
    fi

    # 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

    # Start it up
    su $DAEMON_USER -s /bin/bash -c "$CATALINA_HOME/bin/startup.sh" >"$CATALINA_BASE/logs/start.log" 2>&1
    sleep 1
    if atsIsRunning ; then
      rc_failed 0

      # Check if we need to copy the Signing Certificate to the webapp folder
      if [ ! -f /srv/www/casaats/webapps/CasaAuthTokenSvc/SigningCert ]; then
        # Wait a max of 60 seconds for the webapp folder to be created
          wait_sec=60
          while [ "$wait_sec" != "0" ] ; do
            sleep 1
            if [ -d /srv/www/casaats/webapps/CasaAuthTokenSvc ]; then
              # The folder was created, end the loop
              wait_sec=0
              break
            fi
            wait_sec=$((wait_sec -1))
          done

          # Copy the signing certificate to the webapps folder so that it can be downloaded from the ATS
          cp /etc/CASA/authtoken/keys/localSigningCert /srv/www/casaats/webapps/CasaAuthTokenSvc/SigningCert
      fi
    else
      rc_failed 7
    fi    
  fi
  rc_status -v
}


StopDAEMON()
{
  # Stop the daemon
  echo -n "Stopping casa_atsd..."
  ## Stop daemon with killproc(8) and if this fails
  ## set echo the echo return value.
  if atsIsRunning ; then
    su $DAEMON_USER -s /bin/bash -c "$CATALINA_HOME/bin/shutdown.sh" >"$CATALINA_BASE/logs/stop.log" 2>&1
    # wait 60 sec for stop at maximum
    wait_sec=60
    while [ "$wait_sec" != "0" ] ; do
      sleep 1
      if ! atsIsRunning ; then
        # the server is stopped, end the loop
        wait_sec=0
        break
      fi
      wait_sec=$((wait_sec -1))
    done
    # check the final status
    if atsIsRunning ; then
      rc_failed 1
    else
      rc_failed 0
    fi
  else
    rc_failed 0
  fi  
  # Remember status and be verbose
  rc_status -v
}


# Source the environments file for our daemon
. /etc/CASA/authtoken/svc/envvars
  

case "$1" in
start)
  StartDAEMON
  ;;
stop)
  StopDAEMON
  ;;
restart|reload|force-reload)
  StopDAEMON
  sleep 1
  StartDAEMON
  ;;
status)
  echo -n "Checking for casa_atsd"
  ## Check status with checkproc(8), if process is running
  ## checkproc will return with exit status 0.

  # Status has a slightly different for the status command:
  # 0 - service running
  # 1 - service dead, but /var/run/  pid  file exists
  # 2 - service dead, but /var/lock/ lock file exists
  # 3 - service not running

  # NOTE: checkproc returns LSB compliant status values.
  if atsIsRunning ; then
    rc_failed 0
  else
    rc_failed 3
  fi
  rc_status -v
  ;;
*)
  echo -n "Usage: $0 {start|stop|restart|reload|force-reload}"
  exit 1
  ;;
esac
rc_exit

