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

VDRCFG_FILE="/etc/conf.d/vdr"
PLG_INFO="/etc/vdr/plugins/admin/plugins.info"
ALL_CFG="/tmp/~allcfg"
USE_PLG="/tmp/~useplg"
SEQ_PLG="/tmp/~seqplg"
rm -f $ALL_CFG
rm -f $USE_PLG
rm -f $SEQ_PLG
PLG_SEQ=""

MYNAME="$ADMIN_SCRIPT_PATH/cfgplg.sh"

if [ "$1" != "" ] ; then
   PLG_BASE=$USE_PLG
   NUM_PLG=$(echo $* | wc -w)
   PLGPOS=$NUM_PLG
   for i in $* ; do
      if [ "$(ls ${VDR_LIB}/libvdr-${i}.so.*)" != ""  ] ; then
         echo "$MYNAME:PLG_${i}:$PLGPOS:I:0:0,999::" >> $USE_PLG
         PLGPOS=$(($PLGPOS - 1))
      fi   
   done
else
   PLG_BASE=$ADMIN_CFG_FILE
fi
#set -x
ALL_PLG_LIB=$(ls ${VDR_LIB}/libvdr*.so* | sed -e "s/.*libvdr-//" | cut -f 1 -d ".")
#echo "<$ALL_PLG_LIB>"
#set +x

for i in $ALL_PLG_LIB ; do
   VAL=$(grep -m 1 ":PLG_${i}:" $PLG_BASE | cut -f 3 -d ":")
   if [ "$VAL" = "" ] ; then
      VAL=0
   else
      if [ $VAL -gt 0 ] ; then
         echo "${VAL}:$i" >> $SEQ_PLG
      fi
   fi
   INFO=$(grep "^$i " $PLG_INFO |cut -f 2- -d " ")
   echo "$MYNAME:PLG_${i}:${VAL}:I:0:0,999:${i}:" >> $ALL_CFG
done

sed -i $ADMIN_CFG_FILE -e "/cfgplg.sh:PLG_*/d" -e "/^:.*Plugins$/d" 
   # if PLG variable change PLUGINS in /etc/conf.d/vdr
PLGS=$(sort -nr -k 1 -t ":" $SEQ_PLG | cut -f 2 -d ":" | tr "\r\n" "  ")
   
if [ -s $ALL_CFG ] ; then
   echo ":Plugins" >> $ADMIN_CFG_FILE
   grep -v ":0:I:" $ALL_CFG | sort -nr -k 3 -t ":" >> $ADMIN_CFG_FILE
   grep ":0:I:" $ALL_CFG | sort >> $ADMIN_CFG_FILE
fi
if [ -f $VDRCFG_FILE ] ; then
   if [ "$PLGS" != "$PLUGINS" ] ; then
      sed -i $VDRCFG_FILE -e "s/^PLUGINS=.*/PLUGINS=\"$PLGS\"/"
   fi   
fi

echo "Installed plugins: $PLGS"

echo 'Done!'
exit 0
