#!/bin/bash
#
# chkconfig:    345 31 69
# description:  asterisk webserver
#
### BEGIN INIT INFO
# Provides:          asterisk httpd
# Required-Start:    $syslog $network $remote_fs
# Required-Stop:     $syslog $network $remote_fs
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: asterisk webserver
# Description:       asterisk, a HTTP and reverse proxy server
### END INIT INFO

ASTERISK_BIN=/usr/sbin/asterisk
SAFE_ASTERISK=/usr/sbin/safe_asterisk
ASTERISK_PID=/var/run/asterisk.pid

if [ -r /etc/rc.status ]
then
  source /etc/rc.status
  START="/sbin/startproc"
  STATUS="/sbin/checkproc"
  SUCCESS="echo \$rc_done"
  FAILURE="echo \$rc_failed"
else
  source /etc/rc.d/init.d/functions
  START="daemon"
  STATUS="status"
  SUCCESS="success; echo"
  FAILURE="failure; echo"
fi

[ -r /etc/sysconfig/asterisk ] && source /etc/sysconfig/asterisk

DAEMON=$ASTERISK_BIN
if [ -x $SAFE_ASTERISK ] ; then
  DAEMON=$SAFE_ASTERISK
fi

ASTARGS="-U ${AST_USER:-asterisk} -G ${AST_GROUP:-asterisk}"

if [ $ALTCONF ]; then
  ASTARGS="$ASTARGS -C $ALTCONF"
fi

if [ "x$COREDUMP" = "xyes" ]; then
  ASTARGS="$ASTARGS -g"
fi

if [ "0$MAXLOAD" -gt "0" ]; then
  ASTARGS="$ASTARGS -L $MAXLOAD"
fi

if [ "0$MAXCALLS" -gt "0" ]; then
  ASTARGS="$ASTARGS -M $MAXCALLS"
fi

if [ "0$VERBOSITY" -gt "0" ]; then
  for i in `seq 1 $VERBOSITY`; do
    ASTARGS="$ASTARGS -v"
  done
fi

if [ "x$INTERNALTIMING" = "xyes" ]; then
  ASTARGS="$ASTARGS -I"
fi

if [ "x$TEMPRECORDINGLOCATION" = "xyes" -o "x$TMPRECORDINGLOCATION" = "xyes" ]; then
  ASTARGS="$ASTARGS -t"
fi

RETVAL=0

case "$1" in
  start)
    echo -n "Starting asterisk: "
    if [ "x$COLOR" = "xyes" ]; then
      export TERM=linux
      ${START} sh -c "$DAEMON $ASTARGS -c" >/dev/null </dev/null 2>&1 &
    else
      ${START} $DAEMON $ASTARGS
    fi
    RETVAL=$?
    ;;
  stop)
    echo -n "Stopping asterisk: "
    ${ASTERISK_BIN} -rx 'core stop now' 2> /dev/null
    RETVAL=$?
    ;;
  restart)
    $0 stop
    $0 start
    unset RETVAL
    ;;
  reload)
    echo -n "Reloading configuration of asterisk: "
    ${ASTERISK_BIN} -rx 'core reload' 2> /dev/null
    RETVAL=$?
    ;;
  status)
    echo -n "Status of asterisk: "
    ${ASTERISK_BIN} -rx 'core show version' > /dev/null 2>&1
    RETVAL=$?
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|reload}"
    exit 1
    ;;
esac
[ -z ${RETVAL} ] && exit
[ ${RETVAL} -eq 0 ] && eval "${SUCCESS}" || eval "${FAILURE}"
exit ${RETVAL}
