#!/bin/sh

TFTPDIR=/dbox2/tftpboot
BACKUPDIR=/dbox2/backup
DBOXNAME=dbox
DBOX_FTPPASSWORD=dbox2

if [ $# -eq 2 ] ; then
    DBOXNAME=$2
elif [ $# -ne 1 ] ; then
    echo usage: do-flash file.img [dbox-hostname]
    exit 3
fi 

if ping -c 1 $DBOXNAME >/dev/null; then
    echo "$DBOXNAME is online! Backup and reboot will proceed automatically."
    is_alive="yes"
else
    echo "Warning, $DBOXNAME is not online. Backup and automatic reboot not possible."
    is_alive="no"
fi

if [ "$is_alive" = "yes" ] ; then
    if [ ! -d $BACKUPDIR ] ; then
	mkdir -p $BACKUPDIR
    fi
    echo -n "Backing up ${DBOXNAME}:/var/tuxbox in $BACKUPDIR/$DBOXNAME/tuxbox ... "
    cd $BACKUPDIR
    if wget -q --ftp-user=root --ftp-password=$DBOX_FTPPASSWORD --recursive ftp://$DBOXNAME/tuxbox ; then
	echo success!
    else
	echo failed!
    fi
fi

if [ ! -e $TFTPDIR/dboxflasher ] ; then
    echo "FATAL ERROR: $TFTPDIR/dboxflasher does not exist"
    exit 4
fi

if [ `ls -l $1 | awk '{ print $5 }'` -ne "8257536" ] ; then
    echo "FATAL ERROR: Flashfile $1 has wrong size."
    exit 1
fi

cp $1 $TFTPDIR/dboxflash.img

if [ -f $TFTPDIR/u-boot ] ; then
	mv $TFTPDIR/u-boot $TFTPDIR/u-boot.back
fi

ln -s ./dboxflasher $TFTPDIR/u-boot

echo "Flashing $1 at `date`"  >> $TFTPDIR/flash.log

if [ `id -u` -ne 0 ] ; then
    echo must be root to start dhcp
    exit 2
fi

/etc/init.d/dhcpd status && /etc/init.d/dhcpd stop

/etc/init.d/dhcpd start

trap '/etc/init.d/dhcpd stop; rm -f $TFTPDIR/u-boot $TFTPDIR/dboxflash.img; cp -p $TFTPDIR/u-boot.back $TFTPDIR/u-boot' 1 2 3 15 

if [ "$is_alive" = "yes" ] ; then
    echo "Now the dbox will be rebooted, and flashing will be performed."
    wget -q -O /dev/null http://$DBOXNAME/control/reboot
else
    echo "Now start the dbox to flash it"
fi

sleep 60 
echo "1 minute left"
sleep 60

/etc/init.d/dhcpd stop
rm -f $TFTPDIR/u-boot $TFTPDIR/dboxflash.img
cp -p $TFTPDIR/u-boot.back $TFTPDIR/u-boot
echo "Flashing ended normally"  >> $TFTPDIR/flash.log
echo "Finished, dhcp ended"
