#/!bin/sh

json set firmware status=upgradeProcess
### ==== HTTP start here ====

### Check if firmware image exist
[ -f /tmp/V3K9.all ] || {
  echo "Firmware Update: Firmware image not exist."
  json set firmware status=upgradeFail
  exit 1
}

### Checksum
echo "Firmware Update: Checking if the firmware is valid"
rm -f /tmp/firmware_header
dd if=/tmp/V3K9.all of=/tmp/firmware_header bs=1 count=32 >/dev/null 2>&1
SUM_MD5=
	eval `cat /tmp/firmware_header |
	awk '{
	print "SUM_MD5=" $1}'`
##echo "Firmware Update: Extracting firmware..."
dd if=/tmp/V3K9.all of=/tmp/V3K9_unchecked.all bs=42 skip=1 >/dev/null 2>&1

SUM_MD5_MY=
	eval `md5sum /tmp/V3K9_unchecked.all |
	awk '{
	print "SUM_MD5_MY=" $1}'`

#echo "Output the checksum value for test:"
#echo $SUM_MD5
#echo $SUM_MD5_MY

if [ $SUM_MD5 = $SUM_MD5_MY ]
then
  echo "Firmware Update: Checksum passed."
  rm -f /tmp/V3K9_unchecked.all
else
  echo "Firmware Update: Checksum error. Abort"
  rm -f /tmp/V3K9_unchecked.all
  rm -f /tmp/V3K9.all
  json set firmware status=firmwareFileInvalid
  exit 1
fi

### Check if upgrade already processing
[ -f /tmp/upgrading_firmware ] && {
  echo "Firmware Update: Another firmware upgrade sequence is processing. Abort."
  json set firmware status=upgradeFail
  exit 1
}
touch /tmp/upgrading_firmware

### Stop processes
##echo "Firmware Update: Shutting down applications"
##### TODO: what apps should be shut down?
# 2130_SHUTDOWN_APPS="ipsec samba miniupnpd rp-l2tpd httpd matrixssl lighttpd telnet dropbear"
SHUTDOWN_APPS="asterisk"
for app in $SHUTDOWN_APPS; do
  [ -x /etc/init.d/$app ] && /etc/init.d/$app stop >/dev/null 2>&1
done

### Prepare firmware
echo "Firmware Update: Writing image to flash. Do not turn off or reboot the machine."
rm -f /tmp/root.ubifs-ubinized
dd if=/tmp/V3K9.all of=/tmp/root.ubifs-ubinized bs=48 skip=1 >/dev/null 2>&1
RETURN_VALUE=$?
if [ $RETURN_VALUE -ne 0 ]
then
	echo "Firmware Update: Image preparing failed. Please upgrade again."
	rm -f /tmp/upgrading_firmware
	json set firmware status=upgradeFail
	exit 1
fi

### Write flash
mtd fw_setenv fs2_status new_fweb
echo "[UPGRADE] Starting writing fs2..." > /dev/console
#mtd write /tmp/root.ubifs-ubinized fs2
#nandwrite -a -m -q /dev/mtd4 /tmp/root.ubifs-ubinized
ubiformat /dev/mtd4 -q -y -s 512 -O 512 -f /tmp/root.ubifs-ubinized
RETURN_VALUE=$?
#echo $RETURN_VALUE
if [ $RETURN_VALUE -ne 0 ]
then
	echo "Firmware Update: Image writing failed. Please upgrade again."
	rm -f /tmp/upgrading_firmware
	json set firmware status=upgradeFail
	exit 1
else
	echo "Firmware Update: Upgrade success."
	mtd fw_setenv fs2_status new_ok
	mtd fw_setenv fwup 1
	echo "[UPGRADE] reboot to upgrade firmware..." > /dev/console
fi

### After upgrade
json set firmware status=upgradeSuccess
echo "Firmware Update: Done."
