#!/bin/sh
#
# Start or stop the Video Disk Recorder.
#
# Written and copyright by Patrick Cernko <errror@gmx.de>
#

PATH=/bin:/usr/bin:/sbin:/usr/sbin

set -e

# the path where you have installed vdr
VDRPATH="/opt/vdr"

# the user, under which vdr should run
VDRUSER=errror

# the tty, where the screen(1) running vdr should be attached
VDRTTY=10



function vdr_running () {
    # this function determines if vdr is running
    # it invokes "$@" on the list of pids if it is running
    # or returns 1 (= status false) if vdr is not running

    # collect all pids containing vdr in command name
    vdrpids=$(pgrep vdr)
    # set up a empty variable later holding the pids of vdr
    vdrpids_clean=
    for p in $vdrpids; do
        # only add a pid to vdrpids_clean if it is NOT the pid
        # of this script
        if [ $p -ne $$ ]; then
            vdrpids_clean="$vdrpids_clean $p"
        fi
    done
    if [ "$vdrpids_clean" == "" ]; then
        # if there are no pids left, vdr is not running
        return 1
    else
        # invoke "$@" on the found pids
        if [ ! -z "$*" ]; then
            # only if is is supplied
            "$@" $vdrpids_clean
        fi
        # and return a "true" status
        return 0
    fi
}

case "${1}" in
    "start")
        echo -n "Starting Video Disk Recorder: vdr"
        if vdr_running; then
            echo -n " (already running ["
            vdr_running echo -n
            echo "])."
            exit 1
        else
            su $VDRUSER -c "screen -d -m -S VDR $VDRPATH/bin/vdrd"
            echo -n " vdr-console"
            openvt -c $VDRTTY -- su $VDRUSER -c "screen -x VDR"
            echo "."
        fi
        ;;
    "stop")
        echo -n "Stopping Video Disk Recorder: "
        if vdr_running; then
            echo "vdr."
            vdr_running kill -TERM
        else
            echo "not running."
            exit 1
        fi
        ;;
    "status")
        echo -n "Video Disk Recorder is ";
        if vdr_running; then
            echo -n "running ["
            vdr_running echo -n
            echo "]."
        else
            echo "not running."
            exit 1
        fi
        ;;
    "restart"|"force-reload")
        "${0}" stop
        "${0}" start
        ;;
    *)
        echo "Usage: ${0} {start|stop|status|restart|force-reload}" >&2
        exit 3
        ;;
esac
