#!/bin/sh
# insmod modules from current directory without having to install them first
source /etc/conf.d/vdr.admin.cfg

LOAD_SCRIPT="/_config/bin/dvbload.sh"
UNLOAD_SCRIPT="/_config/bin/dvbunload.sh"
LOAD_TMPL="$LOAD_SCRIPT.all"

if [ "$1" != "" ] ; then
   DVBOPT=$1
   $SETVAL DVBOPT $1
else
   DVBOPT=`$GETVAL DVBOPT`
fi


rm -f $UNLOAD_SCRIPT $LOAD_SCRIPT

if [ "$DVBOPT" = "1" ] ; then
   if [ ! -s $LOAD_TMPL ] ; then
      echo "$LOAD_TMPL not found"
      exit 1
   fi

   if [ ! -n "$(pidof vdr)" ] ; then
      echo "vdr not running"
      exit 1
   fi

   UNUSED_MODS=""

   for i in `seq 1 5` ; do
      LOADED_MODS=`lsmod | grep -e "0 $" | cut -f 1 -d " "`

      for j in $LOADED_MODS ; do
          if [ -n "`grep \"^\#${j} \" $LOAD_TMPL`" ] ; then
   #          echo "${j} is loaded"
             UNUSED_MODS="$UNUSED_MODS ${j}"
             rmmod ${j}
   #	  echo "cat $LOAD_TMPL | sed '/${j}/d'"
   	  cat $LOAD_TMPL | sed "/#${j} /d" > $LOAD_TMPL.new
   	  mv -f $LOAD_TMPL.new $LOAD_TMPL
          fi
      done
   done

   echo "Unused: <$UNUSED_MODS>"

   cat $LOAD_TMPL | cut -f 2- -d " " > $LOAD_SCRIPT

   rm -f LOAD_TMPL

   USED_MODS=`cat $LOAD_SCRIPT | cut -f 2 -d " "`

   rm -f $UNLOAD_SCRIPT
   rm -f $UNLOAD_SCRIPT.tmp
   for i in $USED_MODS ; do
       echo "rmmod ${i}" > $UNLOAD_SCRIPT.tmp
       cat $UNLOAD_SCRIPT >> $UNLOAD_SCRIPT.tmp 2> /dev/null
       mv -f $UNLOAD_SCRIPT.tmp $UNLOAD_SCRIPT
   done

   chmod +x $UNLOAD_SCRIPT $LOAD_SCRIPT
fi

