#! /bin/sh
### BEGIN INIT INFO
# Provides:          rtpengine-recording-daemon
# Required-Start:    $network $local_fs $remote_fs $syslog
# Required-Stop:     $network $local_fs $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Rtpengine Recording Daemon
# Description:       Recording daemon for RTP and other media streams
### END INIT INFO

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=rtpengine-recording-daemon
DESC="RTP/media recording daemon"

DAEMON=$(which rtpengine-recording)
DEFAULTS=/etc/default/${NAME}

test -f "$DAEMON" || exit 0

. /lib/lsb/init-functions

# Load startup options if available
if [ -f "$DEFAULTS" ]; then
	. "$DEFAULTS" || true
fi

if [ "$RUN_RTPENGINE_RECORDING" != "yes" ]; then
	log_action_msg "rtpengine-recording not yet configured. Edit $DEFAULTS first."
	exit 0
fi
[ -z "$PIDFILE" ] && PIDFILE="/run/rtpengine-recording.pid"

OPTIONS=""
START_OPTIONS=""


[ -z "$CONFIG_FILE" ] || OPTIONS="$OPTIONS --config-file=$CONFIG_FILE"
[ -z "$PIDFILE" ] || OPTIONS="$OPTIONS --pidfile=$PIDFILE"


# check if directory for pid file needs to be created

PIDDIR=$(dirname "$PIDFILE")
DO_DIR_CHOWN=0
if ! test -z "$PIDDIR" && ! test -d "$PIDDIR"; then
	mkdir -p "$PIDDIR"
	DO_DIR_CHOWN=1
fi

# handle requested setuid/setgid

if ! test -z "$SET_USER"; then
	START_OPTIONS="$START_OPTIONS --chuid $SET_USER"
	test "$DO_DIR_CHOWN" = 1 && chown "$SET_USER": "$PIDDIR"
fi

if ! test -z "$SET_GROUP"; then
	START_OPTIONS="$START_OPTIONS --group $SET_GROUP"
	test "$DO_DIR_CHOWN" = 1 && chgrp "$SET_GROUP" "$PIDDIR"
fi

###

case "$1" in
  start)
	rtpengine-recording-nfs-setup start

	log_daemon_msg "Starting $DESC" "$NAME"

	# shellcheck disable=SC2086
	start-stop-daemon --start --quiet --pidfile "$PIDFILE" \
		--exec "$DAEMON" $START_OPTIONS -- $OPTIONS || log_progress_msg " already running"
	log_end_msg $?
	;;
  stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	start-stop-daemon --oknodo --stop --quiet --pidfile $PIDFILE \
		--retry 5 --exec "$DAEMON"
	if [ "$?" -ne 0 ]; then
		return $?
	fi
	rm -f $PIDFILE
	log_end_msg $?
	;;
  force-reload|restart)
	$0 stop
	$0 start
	;;
  status)
	status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
	;;
  *)
	echo "Usage: $0 {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
