#!/bin/sh
# Start or stop HylaFAX

PATH=/sbin:/bin:/usr/sbin:/usr/bin
HYLAFAX_HOME=/var/spool/hylafax
FAXGETTY=/usr/sbin/faxgetty
FAXMODEM=/usr/sbin/faxmodem

if [ -f /etc/default/hylafax ]; then
  . /etc/default/hylafax
fi

test -x /usr/sbin/faxq || exit 0
test -x /usr/sbin/hfaxd || exit 0
test -f /var/spool/hylafax/etc/setup.cache || exit 0

echo_fax_devices()
{
  for device in config.tty[MS][0-9] config.faxCAPI; do
    if [ -f "$device" ]; then
      echo "$device"
    fi
  done
}

case "$1" in
  start)
    echo -n "Starting HylaFAX daemons:"
    echo -n " faxq"
    start-stop-daemon --start --exec /usr/sbin/faxq
    echo -n " hfaxd"
    start-stop-daemon --start --exec /usr/sbin/hfaxd -- -i 4559 -o 4557 -s 444
    cd ${HYLAFAX_HOME}/etc
    devices="`echo_fax_devices`"
    if [ ${USE_FAXGETTY} = "yes" ]; then
      echo -n " faxgetty"
      for device in $devices none; do
        [ "$device" = none ] && continue
        ${FAXGETTY} `echo $device | cut -d . -f 2` &
      done
    else
      echo -n " faxmodem"
      for device in $devices none; do
        [ "$device" = none ] && continue
        ${FAXMODEM} `echo $device | cut -d . -f 2` &
      done
    fi
    echo "."
    ;;
  stop)
    echo -n "Stopping HylaFAX daemons:"
    echo -n " faxq"
    start-stop-daemon --stop --exec /usr/sbin/faxq
    echo -n " hfaxd"
    start-stop-daemon --stop --exec /usr/sbin/hfaxd -- -i 4559 -o 4557 -s 444
    echo -n " faxgetty"
    killall faxgetty 2> /dev/null || true
    echo "."
    ;;
  restart|force-reload)
    echo -n "Restarting HylaFAX daemons:"
    echo -n " faxq"
    start-stop-daemon --stop --exec /usr/sbin/faxq
    sleep 1
    start-stop-daemon --start --exec /usr/sbin/faxq
    echo -n " hfaxd"
    start-stop-daemon --stop --exec /usr/sbin/hfaxd -- -i 4559 -o 4557 -s 444
    sleep 1
    start-stop-daemon --start --exec /usr/sbin/hfaxd -- -i 4559 -o 4557 -s 444
    cd ${HYLAFAX_HOME}/etc
    devices="`echo_fax_devices`"
    if [ ${USE_FAXGETTY} = "yes" ]; then
      echo -n " faxgetty"
      killall faxgetty 2> /dev/null || true
      for device in $devices none; do
        [ "$device" = none ] && continue
        ${FAXGETTY} `echo $device | cut -d . -f 2` &
      done
    else
      echo -n " faxmodem"
      killall faxmodem 2> /dev/null || true
      for device in $devices none; do
        [ "$device" = none ] && continue
        ${FAXMODEM} `echo $device | cut -d . -f 2` &
      done
    fi
    echo "."
    ;;
  *)
    echo "Usage: /etc/init.d/hylafax {start|stop|restart|force-reload}"
    exit 1
    ;;
esac

exit 0
