#!/bin/sh

# runvdr: Loads the DVB driver and runs VDR
#
# If VDR exits abnormally, the driver will be reloaded
# and VDR restarted.
#
# heavily modified for c't-vdr-distro
# Peter Siering, <ps@ctmagazin.de>
#

VDRPRG="vdr"
VDROPT="$*"
VDRCMD="$VDRPRG $VDROPT"
LSMOD="`/sbin/lsmod | grep -w '^dvb' | wc -l`"
KILL="/usr/bin/killall -q -TERM"

DVB11="no"
if [ -e "/etc/modutils/linuxtv-dvb.`uname -r`" ]; then
    DVB11="yes"
fi

if [ "$DVB11" = "yes" ]; then
    modprobe dvb
else
    if [ $LSMOD -eq 0 ] ; then
	modprobe dvb-ttpci vidmode=2 >/dev/null 2>&1
    fi
    # get DVB module stack
    MODULES=`lsmod | grep dvb-core | cut -d'[' -f2 | cut -d']' -f1`
    MODULES="$MODULES dvb-core"
fi

/usr/share/vdr/epgscan.sh &

while (true) do
        # change /dev/null to /tmp/vdr.out
        # for debugging purposes
	eval $VDRCMD 2>/tmp/vdr.err >/dev/null
	RET=$?
	if test $RET -eq 0; then exit; fi
	if test $RET -eq 2; then
	    ERR=`cat /tmp/vdr.err`
	    logger -t runvdr "stopping after fatal fail ($ERR)"
	    exit
	else
	    logger -t runvdr "restarting VDR"
	fi
        $KILL $VDRPRG
        sleep 5
	if [ "$DVB11" = "yes" ]; then
	    modprobe -r dvb
	    sleep 2
	    modprobe dvb
	else
	    for MODUL in $MODULES; do
		rmmod $MODUL >/dev/null 2>&1
		wait `pidof rmmod`
	    done
	    modprobe dvb-ttpci vidmode=2 >/dev/null 2>&1
	fi
done
