#! /bin/sh

WD=`pwd`
ZIPFILE=$1

[ ! -f "$ZIPFILE" ] && {
  echo "Usage: `basename $0` <zipfile>"
  exit
}
[ "`echo $ZIPFILE |cut -c1`" != "/" ] && ZIPFILE="$WD/$ZIPFILE"
OUTFILE=$WD/`basename "$ZIPFILE" | sed -e 's/\.zip/.tar/'`

PATH=$WD:$PATH

rm -rf uitpak inpak
mkdir uitpak
mkdir -p inpak/var/tuxbox/config/enigma

echo "Bezig met uitpakken zipfile"
cd $WD/uitpak && unzip -q "$ZIPFILE" || {
  echo "Fout tijdens uitpakken zipfile"
  exit
}

[ -f $WD/uitpak/services ] && DIR=$WD/uitpak
[ -f $WD/uitpak/*/services ] && DIR=$WD/uitpak/*

[ ! -d $DIR ] && {
  echo "Geen services file gevonden in zipfile"
  exit
}

mv $DIR/satellites.xml $WD/inpak/var/tuxbox/config
mv $DIR/* $WD/inpak/var/tuxbox/config/enigma

cd $WD/inpak && {
  echo "Bezig met maken tar file"
  tar cf "$OUTFILE" var
  rm -f "$OUTFILE.gz"
  echo "Bezig met 'g-zippen' tar file"
  gzip -9 "$OUTFILE"
  rm -rf $WD/uitpak $WD/inpak
  echo "Klaar, tar.gz file is: $OUTFILE.gz"
}
