#!/bin/bash

# sipxacccode - Startup script for sipxacccode

# chkconfig: 35 85 15
# description: sipxacccode is Authorization Code/DISA/Account using FreeSwitch for sipX
# processname: sipxacccode

#
# Copyright (C) 2007 Pingtel Corp., certain elements licensed under a Contributor Agreement.  
# Contributors retain copyright to elements licensed under a Contributor Agreement.
# Licensed to the User under the LGPL license.

. /etc/rc.d/init.d/functions || exit 1
. /usr/lib/sipXecs/sipx-utils.sh || exit 1

prog=sipxacccode
pidfile="/var/run/sipxpbx/sipxacccode.pid"

[ -e /etc/sipxpbx/sysconfig/$prog ] && . /etc/sipxpbx/sysconfig/$prog

checkRunningInstance() {
  if [ -f "${pidfile}" ]; then
    pid=`cat ${pidfile}`
    if checkpid $pid 2>&1; then
      echo "Process $prog is already running with pid $pid"
      exit 1
    fi
  fi
}

start() {
    checkRunningInstance

    JavaCmd=`/usr/bin/sipx-config --java`
    Dependencies=`/usr/bin/java-dep -d /usr/share/java/sipXecs/sipXcommons commons-codec commons-io commons-logging dom4j jaxen log4j mongo sipxcommons`
    export CLASSPATH=`echo /etc/sipxpbx/sipxacccode /usr/share/java/sipXecs/sipXacccode/*.jar ${Dependencies} | sed -e 's/ /:/g'`

    setJavaSslOpts

    # procname is there so cfengine can find it
    Command="$JavaCmd \
      -Dprocname=sipxacccode \
      -Dconf.dir=/etc/sipxpbx \
      -Dlog.dir=/var/log/sipxpbx \
      -Dvar.dir=/var/sipxdata \
      $JavaSslOpts \
      ${SIPXACC_OPTS} \
         org.sipfoundry.sipxacccode.SipXacccode \
	 $Args"
    if [ -n "${NoFork}" ] ; then
      runuser -s /bin/bash sipx -c "${Command}"
    else
      echo -n $"Starting sipxacccode: "
      runuser -s /bin/bash sipx -c "${Command}" >/dev/null 2>&1 &
      echo $! > ${pidfile}
      echo_success
    fi
}

stop() {
  echo -n $"Stopping sipxacccode: "
  killproc -p "${pidfile}" "sipxacccode"
  Status=$?
  echo
  [ $Status -eq 0 ] && rm -f "${pidfile}"
}

restart() {
  stop
  start
}

configtest() {
     sipx_config_exists /etc/sipxpbx/sipxacccode.properties
     Status=$(($Status+$?))

     # Check that the log file is writable.
     logfile="/var/log/sipxpbx/sipxacccode.log"
     if [ -e $logfile -a ! -w $logfile ]
     then
         echo "Log file '$logfile' exists but is not writable." >&2
         Status=1
     fi
}

case "$1" in
  nofork)
    NoFork=1
    start
    ;;
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload|force-reload)
    restart
    ;;
  condrestart)
    [ -f ${pidfile} ] && restart || :
    ;;
  status)
    status -p ${pidfile} sipxacccode
    ;;
  configtest)
    configtest
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|nofork|configtest}"
    Status=1
esac

exit $Status
