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

VDRCFG_FILE="/etc/conf.d/vdr"
NEW_PLUG="/tmp/~newplg"
OLD_PLUG="/tmp/~oldplg"
USE_PLUG="/tmp/~useplg"

MYNAME="$ADMIN_SCRIPT_PATH/cfgplg.sh"

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

rm -f $OLD_PLUG
rm -f $NEW_PLUG
PLG_SEQ=""

for i in $ALL_PLG ; do
   OLDVAL=`cat $ADMIN_CFG_FILE | grep :PLG_${i}:`
   if [ "$OLDVAL" = "" ] ; then
      echo "$MYNAME:PLG_${i}:00:I:2:0,99:Plugin ${i}:" >> $NEW_PLUG
   else
      VAL=`echo $OLDVAL | cut -f 3 -d ":"`
    	 echo "$VAL|$OLDVAL" >> $OLD_PLUG
      if [ "$VAL" != "00" ] ; then
    	    echo "$VAL|${i}" >> $USE_PLUG
      fi
   fi
done
sed -i $ADMIN_CFG_FILE -e "/cfgplg.sh:PLG_*/d"
if [ -s $NEW_PLUG ] ; then
   cat $NEW_PLUG >> $ADMIN_CFG_FILE
   rm -f $NEW_PLUG
fi
if [ -s $OLD_PLUG ] ; then
   cat $OLD_PLUG | sort -r | cut -f 2 -d "|" >> $ADMIN_CFG_FILE
   rm -f $OLD_PLUG
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
