#!/bin/bash
#
source /etc/conf.d/vdr.admin.cfg
source /etc/conf.d/vdr

if [ "$1" != "" ] && [ -f $1 ] ; then
   PLG_BASE="$1"
else
   PLG_BASE=$ADMIN_CFG_FILE
fi

VDRCFG_FILE="/etc/conf.d/vdr"
ALL_CFG="/tmp/~allcfg"
USED_CFG="/tmp/~usedcfg"
USE_PLUG="/tmp/~useplg"

MYNAME="$ADMIN_SCRIPT_PATH/cfgplg.sh"

ALL_PLG_LIB=$(ls /usr/lib/vdr/libvdr*.so | sed 's/\.so//' | cut -f 5 -d "/" | sed 's/libvdr-//')
#echo "<$ALL_PLG_LIB>"

rm -f $ALL_CFG
rm -f $USED_CFG
rm -f $USE_PLUG
PLG_SEQ=""

for i in $ALL_PLG_LIB ; do
   OLDVAL=$(grep -m 1 ":PLG_${i}:" $PLG_BASE)
   if [ "$OLDVAL" = "" ] ; then
      echo "$MYNAME:PLG_${i}:00:I:2:0,99:Plugin ${i}:" >> $ALL_CFG
   else
      VAL=$(echo $OLDVAL | cut -f 3 -d ":")
      if [ "$VAL" != "00" ] ; then
         echo "$VAL|${i}" >> $USE_PLUG
         echo "$VAL|$OLDVAL" >> $USED_CFG
      fi
      echo "$OLDVAL" >> $ALL_CFG
   fi
done
sed -i $ADMIN_CFG_FILE -e "/cfgplg.sh:PLG_*/d" -e "/^:.*Plugins$/d" 
if [ -s $USED_CFG ] ; then
   echo ":Installierte Plugins" >> $ADMIN_CFG_FILE
   cat $USED_CFG | sort -r | cut -f 2 -d "|" >> $ADMIN_CFG_FILE
#   rm -f $USED_CFG
fi
if [ -s $ALL_CFG ] ; then
   echo ":Verfuegbare Plugins" >> $ADMIN_CFG_FILE
   cat $ALL_CFG >> $ADMIN_CFG_FILE
#   rm -f $USED_CFG
fi
if [ -s $USE_PLUG ] ; then
   PLG_SEQ=`cat $USE_PLUG | sort -r | cut -f 2 -d "|" | tr '\r\n' '  '`
   rm -f $USE_PLUG
fi
if [ -f $VDRCFG_FILE ] ; then
   sed -i $VDRCFG_FILE -e "s/^PLUGINS=.*/PLUGINS=\"$PLG_SEQ\"/"
fi

echo "Installed plugins: $PLG_SEQ"

echo 'Done!'
exit 0
