#!/bin/sh

cd /var/update

rm -rf update.sh update.sh.sig mixer.img system.img boot.img

unzip -o "$1" update.sh update.sh.sig mixer.img system.img
unzip -o "$1" boot.img boot.img.sig
unzip -o "$1" inittab hostapdproxy udhcpdproxy
chmod a+x update.sh

if [ -f /var/update/boot.img ]; then
    /bin/verifyfile /var/update/boot.img && ( cat /var/update/boot.img >/dev/mmcblk0p6 )
fi

sync

rm -rf /mixer.img.old
rm -rf /system.img.old

mv /mixer.img /mixer.img.old
mv /system.img /system.img.old
sync

mv /var/update/mixer.img  /mixer.img
mv /var/update/system.img /system.img

sync

if [ "`md5sum /etc/inittab`" == "00c08a00b29e4183ec09aa516f61adfc  /etc/inittab" ] || [ ! -f /sbin/hostapdproxy ]; then
    mount -o ro /dev/mmcblk0p7 /mnt
    mount -o remount,rw /mnt
    if [ -f /var/update/inittab ] && [ -f /var/update/hostapdproxy ] && [ -f /var/update/udhcpdproxy ]; then
        cp -f /var/update/inittab /mnt/etc/inittab
        cp -f /var/update/hostapdproxy /mnt/sbin/hostapdproxy
        cp -f /var/update/udhcpdproxy /mnt/sbin/udhcpdproxy
        chmod 755 /mnt/sbin/hostapdproxy /mnt/sbin/udhcpdproxy
    fi
    sync
    mount -o remount,ro /mnt
fi

echo -n ~\$FIRMWARE_UPDATED >/var/update/message.txt

exit 0
