#! /bin/sh

root=/var/InternerSpeicher
home=$root/fhem

echo "########################### FHEM INSTALL BEGIN #######################"
killall perl > /dev/null 2>&1
sleep 1

echo "########################### Extracting fhem.tar.gz ###################"
cd $root

if test -d fhem; then
  odir=fhem.old.`date +%Y-%m-%d_%H:%M:%S`
  mv fhem $odir
fi

gzip -cd /var/fhem.tar.gz | tar xf -

cd $root

# Save files from the AVM Style installation
if test -f $odir/etc/fhem.cfg; then
  echo "########################### Converting chroot style config ###########"
  export LD_LIBRARY_PATH=$home/lib
  export PERL5LIB=$home/lib/perl5/site_perl/5.12.2/mips-linux:$home/lib/perl5/site_perl/5.12.2:$home/lib/perl5/5.12.2/mips-linux:$home/lib/perl5/5.12.2
  cp $odir/etc/fhem.cfg fhem
  fhem/perl -pi -e 's,/usr/share/fhem,'$home',g;
                    s,/var/log/fhem,'$home'/log,;
                    s,^#define autocreate,define autocreate,;
                    s,^#attr autocreate,attr autocreate,;
                    s,ttyACM(.)(@\d+)?,ttyACM$1\@38400,;' fhem/fhem.cfg
  mv $odir/var/log/fhem/* fhem/log
fi

# Save files from our old version
if test -f $odir/fhem.cfg; then
  mv $odir/FHEM/*.sh fhem/FHEM
  mv $odir/FHEM/99.*Util.pm fhem/FHEM
  mv $odir/FHEM/*.sh fhem/FHEM
  mv $odir/log/* fhem/log
  mv $odir/*.cfg fhem
fi
chown -R boxusr80:root $home

cat /var/flash/debug.cfg > /var/nvi.tmp
grep -q fhem /var/nvi.tmp
r=$?
if test $r != 0; then
  echo "########################### Modifying the startup script #############"
  echo $home/startfhem >> /var/nvi.tmp
  cat /var/nvi.tmp > /var/flash/debug.cfg
fi
rm -f /var/nvi.tmp

# We have to restart with exit code 1, else the frontend tells us:
# update failed: no error
echo "########################### FHEM INSTALL END #########################"
exit 1
