#!/bin/bash
#
#

. /usr/lib/vdr/config-loader.sh

OPTIONS="$*"
if [ "$NONPTL" = "1" -a `uname -m` != x86_64 ]; then
    VDRCMD="LANG=$VDR_LANG LC_ALL=$VDR_LANG LD_ASSUME_KERNEL=2.4.1 /usr/bin/vdr $OPTIONS"
else
    VDRCMD="LANG=$VDR_LANG LC_ALL=$VDR_LANG /usr/bin/vdr $OPTIONS"
fi

function get_modulenames ()
{
    KVERS=`uname -r | grep -e '2.6'`
    if [ -z "$KVERS" ]; then
        MODULES=`lsmod | grep dvb-core | cut -d'[' -f2 | cut -d']' -f1`
    else
        MODULES=`lsmod | grep ^dvb_core | awk '{print $4;}' | awk '{ gsub(/,/," ", $1); print }'`
    fi
}

function set_permissions ()
{
    for FILE in av7110_ir budget_ci_ir; do
        if [ -e "/proc/$FILE" ]; then
            chown $USER.$GROUP /proc/$FILE
        fi
    done
}

get_modulenames

if [ -z "$MODULES" ]; then               # If no DVB-Modules were found, try to load
    modprobe dvb > /dev/null 2>&1        # the module with the name dvb, this could
    get_modulenames                      # be an alias for the dvb-ttpci-module or
fi                                       # another dvb-module

MODULES="$MODULES dvb-core"

while (true) do
    set_permissions
    eval $VDRCMD >/dev/null 2>&1
    if test $? -eq 0; then exit; fi
    logger "restarting VDR"
    /usr/bin/killall -q -TERM /usr/bin/vdr
    sleep 10

    for MODULE in $MODULES; do
        rmmod $MODULE >/dev/null 2>&1
        wait `pidof rmmod`
    done

    for MODULE in $MODULES; do
        modprobe $MODULE >/dev/null 2>&1
    done
done
