#!/bin/sh
LOG="/_config/update/update.log"
URL="www.htpc-forum.de/gen2vdr/1.1/fixes"
URL_TEST="www.htpc-forum.de/test/1.1/fixes"

MD5_FILE="g2v_md5_fixes"

cd /_config/update

if [ "$1" = "-media" ] ; then
   MEDIA_MD5=$(find /media -name $MD5_FILE -type f)
   [ "$MEDIA_MD5" == "" ] && echo "$MD5_FILE nicht vorhanden" && exit 1
   rm -f $MD5_FILE >/dev/null 2>&1
   MEDIA_PATH=$(dirname $MEDIA_MD5)
   cp -f "$MEDIA_MD5" .
elif [ "$1" != "-l" ] ; then
   if [ "$1" = "-t" ] ; then   
      URL=$URL_TEST
   fi
   rm -f $MD5_FILE >/dev/null 2>&1
   wget "${URL}/${MD5_FILE}"
fi
ARCHS=$(grep "\.tar\.bz2" $MD5_FILE | cut -f 3 -d " ")

for i in $ARCHS ; do
   [ "$i" = "g2v_cdupdate.tar.bz2" ] && continue
   if [ "$(grep "$i" .blacklist 2> /dev/null)" = "$i" ] ; then
      echo "<$i> ist auf der schwarzen Liste"
      continue
   fi
   if [ -f ${i} ] ; then
      echo "Checking md5sum <${i}> ..."
      MD5=$(md5sum ${i} | cut -f 1 -d " ")
      if [ "$(grep ${i} ${MD5_FILE} | grep $MD5)" != "" ] ; then
         if [ "$1" != "-f" ];  then
            echo "$i bereits verarbeitet"
	    continue
         fi
      else
         rm -f ${i}
      fi    
   fi
   if [ ! -f ${i} ] ; then
      if [ "$1" != "-media" ] ; then
         echo "Downloading <${i}> ..." | tee -a $LOG
         wget ${URL}/${i}
         FN=$i
      else
         cp -f $MEDIA_PATH/$i /_config/update/
      fi   
   fi      
   MD5=$(md5sum ${i} | cut -f 1 -d " ")
   if [ "$(grep ${i} ${MD5_FILE} | grep $MD5)" = "" ] ; then
      logger -s "Fehler bei Download/Kopieren von ${i}"
      exit -1
   fi
   logger -s "Entpacke <$i>"            
   tar -C / -xjvf $i 2>&1 | tee -a $LOG
   INST_SCRIPT=$(echo $i| sed -e "s/.tar.bz2/.sh/")
   if [ -f $INST_SCRIPT ] ; then
      logger -s "Starte <$INST_SCRIPT>"            
      sh $INST_SCRIPT 2>&1 | tee -a $LOG
   fi
done
if [ "$(pidof vdr)" = "" ] ; then
   /etc/init.d/vdr start
fi

