#!/usr/local/bin/bash
#
# Copyright (C) 2005 SIPfoundry Inc.
# Licensed by SIPfoundry under the LGPL license.
#
# Copyright (C) 2005 Pingtel Corp.
# Licensed to SIPfoundry under a Contributor Agreement.

Action=RUN
Status=0
Args=""

while [ $# -ne 0 ]
do
    case ${1} in
        --configtest)
            Action=CONFIGTEST
            ;;

        *)
            Args="$Args $1"
            ;;
    esac           

    shift # always consume 1
done

CONFIG_DEFS="/usr/local/etc/sipxpbx/config.defs"

CONFIG_FILES="\
  /usr/local/etc/sipxpbx/sipxpresence-config \
  "

# If the "config.defs" file exists and the <name>.in file exists for a
# configuration file, then run the config preprocessor to generate the
# fully resolved configuration file.
if [ -f "$CONFIG_DEFS" ]
then
  for i in $CONFIG_FILES ; do
    if [ -f "${i}.in" ]
    then
       /usr/local/bin/configpp --defs "${CONFIG_DEFS}" --in "${i}.in" --out "$i"
    fi
  done
fi

case ${Action} in
   RUN)
     echo $$ > /var/run/sipxpbx/sipxpresence.pid
     exec /usr/local/bin/sipxpresence $Args
     ;;

   CONFIGTEST)
     Status=0

     #/usr/local/bin/sipx-validate-xml /usr/local/etc/sipxpbx/sipxpresence-config.xml
     #Status=$(($Status+$?))

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

     ;;
esac

exit $Status
