#!/bin/bash
#
source /etc/conf.d/vdr.admin.cfg
BACKUP_DIR="/mnt/hda5/g2v-backup"
OLD_ADMIN_CFG_FILE="$BACKUP_DIR/etc/vdr/plugins/admin/admin.conf"

checkvar() {
   OVAL=$(grep -m 1 ":$1:" $OLD_ADMIN_CFG_FILE | grep ":$1:" | cut -f 3 -d ":")
   OTYPE=$(grep -m 1 ":$1:" $OLD_ADMIN_CFG_FILE | grep ":$1:" | cut -f 4 -d ":")
   if [ "$OTYPE" != "" ] && [ "$OVAL" != "" ] ; then
      if [ "$OTYPE" = "L" ] ; then 
         OVAL=$(grep ":$1:" $OLD_ADMIN_CFG_FILE | cut -f 6 -d ":" | cut -f $(($OVAL+1)) -d "," )
         if [ "$OVAL" = "" ] ; then
            echo "<$1> ungueltig"
            return
         fi
      fi
   else
      echo "<$1> nicht gefunden"
   fi

   OLDVAL=$(echo $OVAL | sed -e 's/^ //g' -e 's/ $//g')
   NEWVAL=$($GETVAL $1)

   if [ "$OLDVAL" != "$NEWVAL" ] ; then
      echo ""
      echo "Setze <$1> von <$NEWVAL> auf <$OLDVAL>"
      $SETVAL $1 "$OLDVAL"
   fi
   if [ "$1" = "LIRC" ] ; then 
      if [ "$OLDVAL" != "Tastatur" ] && [ -f $BACKUP_DIR/etc/lircd.conf ] ; then
         cp -vf $BACKUP_DIR/etc/lircd.conf /etc/
      fi
      if [ -f $BACKUP_DIR/etc/vdr/remote.conf ] ; then
         cp -vf $BACKUP_DIR/etc/vdr/remote.conf /_config/install/vdr/remote.conf
         cp -vf $BACKUP_DIR/etc/vdr/remote.conf /_config/install/vdr/remote.conf.activy
      fi
   elif [ "$1" = "RCV" ] ; then 
      if [ -f $BACKUP_DIR/etc/vdr/channels.conf ] ; then
         OLD_CC=$(sed -e "/^:.*/d" $BACKUP_DIR/etc/vdr/channels.conf | head -n 1 |  sed -e "s/[^:]//g" | wc -c)
         NEW_CC=$(sed -e "/^:.*/d" /_config/install/vdr/channels.conf.sat | head -n 1 |  sed -e "s/[^:]//g" | wc -c)
         if [ "$OLD_CC" = "$NEW_CC" ] ; then
            if [ "$OLDVAL" = "SAT" ] ; then
               RCV="sat"
            elif [ "$OLDVAL" = "Kabel" ] ; then
               RCV="cable"
            else
               RCV="terr"
            fi
            cp -vf $BACKUP_DIR/etc/vdr/channels.conf /_config/install/vdr/channels.conf.$RCV
         else 
            echo "Format der channels.conf unterschiedlich"
         fi
      fi
   fi
}

if [ -f $OLD_ADMIN_CFG_FILE ] ; then
   echo "Alte Konfiguration wird migriert ..."

   OLDVARS=$(grep "^/" $OLD_ADMIN_CFG_FILE | cut -f 2 -d ":")

   for i in $OLDVARS ; do
      checkvar $i
   done
else   

   echo "Nichts zum migrieren gefunden"
fi
