#!/bin/sh
##
## Setup a supervised Apache Tomcat service
## Copyright (c) 2015-2017 SATOH Fumiyasu @ OSS Technology Corp., Japan
##               <http://www.osstech.co.jp/>
##
## License: GNU General Public License version 3 or later
##

set -u
umask 0022

## Options
## ======================================================================

root="${TOMCAT_INSTANCE_SVCONF_ROOT-}"
sv_cmd="/opt/osstech/sbin/tomcat-instance"
sv_configfile="/opt/osstech/etc/tomcat/tomcat.conf"
sv_configdir="/opt/osstech/etc/tomcat/tomcat.conf.d"
sv_env="
  NICE
  IONICE
  MEMORYLIMIT
  DATALIMIT
  STACKLIMIT
  OPENFILELIMIT
  COREFILELIMIT
  COMMAND
  ARGV0
  CONFIGFILE
  CONFIGDIR
  OPTIONS
"

if [ $# -lt 1 ] && [ $# -gt 2 ]; then
  echo "Usage: $0 /SVDIR [CONFIGFILE]" 1>&2
  exit 1
fi

sv_dir="$1"; shift
[ $# -ge 1 ] && { sv_configfile="$1"; shift; }

## Create service directory
## ======================================================================

mkdir "$root$sv_dir" || exit $?
mkdir "$root$sv_dir/env" || exit $?

## The "once" is an OSSTech-specific file and is used by
## /etc/init.d/svinit, not for supervise(8).
touch "$root$sv_dir/down" "$root$sv_dir/once" || exit $?

for env in $sv_env; do
  touch "$root$sv_dir/env/$env" || exit $?
done
echo "$sv_cmd" >"$root$sv_dir/env/COMMAND" || exit $?
echo "$sv_configfile" >"$root$sv_dir/env/CONFIGFILE" || exit $?
echo "$sv_configdir" >"$root$sv_dir/env/CONFIGDIR" || exit $?
echo "16384" >"$root$sv_dir/env/OPENFILELIMIT" || exit $?

## NOTE: $OPENFDLIMIT is for backward compatibility
cat <<'EOT_SV_RUN' >"$root$sv_dir/run" || exit $?
#!/bin/sh
exec 2>&1
exec envdir ./env sh -c '
  ${WORKINGDIR:+cd} ${WORKINGDIR:+"$WORKINGDIR"}
  echo "PID: $$"
  env |sort |sed "s/^/Environment: /"
  CATALINA_BASE=`
    [ -f "$CONFIGFILE" ] && . "$CONFIGFILE"
    for configfile in "$CONFIGDIR"/*.conf; do
      [ -f "$configfile" ] && . "$configfile"
    done
    echo "$CATALINA_BASE"
  `
  set -- \
    ${NICE:+nice} ${NICE:+-n} ${NICE:+"$NICE"} \
    ${IONICE:+ionice} ${IONICE:+-n} ${IONICE:+"$IONICE"} \
    softlimit \
      ${MEMORYLIMIT:+"-m$MEMORYLIMIT"} \
      ${DATALIMIT:+"-d$DATALIMIT"} \
      ${STACKLIMIT:+"-s$STACKLIMIT"} \
      ${OPENFILELIMIT:+"-o$OPENFILELIMIT"} \
      ${OPENFDLIMIT:+"-o$OPENFDLIMIT"} \
      ${COREFILELIMIT:+"-c$COREFILELIMIT"} \
    argv0 \
    "$COMMAND" \
    "${ARGV0:-sv:`pwd`}" \
      run \
      ${CATALINA_BASE:+"$CATALINA_BASE"} \
      $OPTIONS \
    ;
  ## ksh: Ensure that all commands in the pipeline are terminated
  wait
  echo "Execute: $@"
  exec "$@"
'
EOT_SV_RUN
chmod 0755 "$root$sv_dir/run" || exit $?

## The "notify" is for supervise(8) in daemontools-encore, not daemontools
cat <<'EOT_SV_NOTIFY' >"$root$sv_dir/notify" || exit $?
#!/bin/sh
echo "Notify: script=$1 status=$2 pid=$3 exit=$4"
EOT_SV_NOTIFY
chmod 0755 "$root$sv_dir/notify" || exit $?

exit 0
