#!/bin/sh
### BEGIN INIT INFO
# Provides:             sipwitchd
# Required-Start:       $local_fs $network $syslog $remote_fs $named
# Required-Stop:        $local_fs $network $syslog $remote_fs $named
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Start and stop sipwitchqt service daemon.
# Description:          This script manages startup and shutdown for
#                       SipWitchQt, a SIP telephony service daemon.
### END INIT INFO
#
# Copyright (C) 2018-2019 David Sugar, Tycho Softworks.
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# sipwitchqt      This shell script takes care of starting and stopping
#                 a sipwitch server running as a system service.
#
# chkconfig: - 95 15
# description: SipWitchQt telephony service.

DAEMON="/usr/sbin/sipwitchqt-server"
NAME="sipwitchqt"
DESC="sipwitchd server"
DEFAULT="/etc/default/$NAME"
PIDFILE="/var/run/$NAME.pid"
OPTIONS="--quiet --chuid sipwitch --pidfile $PIDFILE"
START="1"

# Exit if service not installed
test -x "$DAEMON" || exit 0

# Read config variables if present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

. /lib/lsb/init-functions

case "$1" in
start)
    if [ "$START" = "0" ] ; then
        exit 0
    fi
    echo -n "Starting $NAME: "
    start-stop-daemon --start --background --make-pid $OPTIONS \
        --group sipwitch --exec $DAEMON &>/dev/null
    echo "$?"
    ;;
stop)
    echo -n "Stopping $NAME: "
    start-stop-daemon --stop $OPTIONS --remove-pidfile \
        --signal INT --retry=TERM/30/KILL/5 --exec $DAEMON
    echo "$?"
    ;;
status)
    echo -n "Status $NAME: "
    start-stop-daemon --status $OPTIONS && exit_status=$? || exit_status=$?
    case "$exit_status" in
    0) 
        echo "running"
        ;;
    1)
        echo "stopped but pid file exists"
        ;;
    3)
        echo "stopped"
        ;;
    4)
        echo "status unknown"
        ;;
    esac
    exit $exit_status
    ;;
reload)
    echo -n "Reloading $NAME: "
    start-stop-daemon --signal HUP $OPTIONS
    echo "$?"
    ;;
restart|force-reload)
    $0 stop
    $0 start
    ;;
try-restart)
    $0 status >/dev/null 2>&1 && $0 restart
	;;
*)
    echo "Usage: $0 {start|stop|restart|reload|force-reload|try-restart|status}" >&2
    exit 1
    ;;
esac

exit 0

