#!/bin/bash
#
# init.d script to manage a container based on an OSGi framework
#
# Generated by PAX Runner
#
set -e # stop on errors
#
#              <startlevels> <startprio> <stopprio>
# chkconfig:   2345 80 80
# description: The PAX_RUNNER_APPNAME application
#
# NOTE: the 2 comments above and the following 4 variable values will propably
#       need customization when packaging the distribution. The generated values
#       are meant for local testing
#
app_name=PAX_RUNNER_APPNAME
app_root=PAX_RUNNER_APPROOT
pid_file=${app_root}/${app_name}.pid
log_file=${app_root}/${app_name}.log
#
# ... here we go ...
#
# - get PID from .pid file if it exists and check if it is running
#
pid=`[[ -e ${pid_file} ]] && cat ${pid_file} || echo "NO_PID_FILE"`
set +e # disable because egrep will return 1 on mismatch
pid_isrunning=`ps -eo pid | egrep ^[[:space:]]*${pid}$`
set -e # reenable
#
# - functions to start/stop the container ...
#
function startContainer() {
  if [ -z ${pid_isrunning} ]; then
    echo "starting ${app_name}"
    pushd ${app_root} > /dev/null
PAX_RUNNER_STARTCODE
    echo $! > ${pid_file}
    popd > /dev/null
  else
    echo "${app_name} already running with pid ${pid}"
  fi
}
#
function stopContainer() {
  if [ ! -z ${pid_isrunning} ]; then
    echo "stopping ${app_name} with pid ${pid}"
    kill `cat ${pid_file}`
  else
    echo "${app_name} not running"
  fi
}
#
# - main command dispatch ...
#
case "$1" in
    start)
      startContainer
      ;;
    stop)
      stopContainer
      ;;
    restart)
      stopContainer
      startContainer
      ;;
    status)
      if [ ! -z ${pid_isrunning} ]; then
        echo "${app_name} is running with pid ${pid}"
      else
        echo "${app_name} not running"
      fi
      ;;
    *)
      echo "Usage: ${app_name} {start|stop|restart|status}"
      exit 1
      ;;
esac
#
exit 0
