#! /bin/bash
### BEGIN INIT INFO
# Provides:          jogglerflash
# Required-Start:    $local_fs $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Reflash Joggler internal memory
# Description:       Reflash Joggler internal memory
### END INIT INFO

NAME=jogglerflash

case "$1" in
  start)


	SVR="o2.openpeak.co.uk"
	URL="http://o2.openpeak.co.uk/firmware/"
	IMG="app-o2flash-26635.8686-S3-f1-reimage.tgz"
	IMGLOC="/boot/reflash"
	IMGSUM="50b728cd04ef9e9ac4be6ac83d22a5fb"
	RFCOMP="/var/reflash"


	clear
	echo
	echo
	tput setaf 6
	echo "                                                              O2 Joggler Firmware Reflash v1.09"
	[ ! -e $IMGLOC/test ] && echo "==============================================================================================="
	[ -e $IMGLOC/test ] && echo "=========  TEST MODE  ========================================================================="
	echo "                                                                           birdslikewires.co.uk"
	tput sgr0
	echo
	echo
	
	setterm -powersave off
	setterm -blank 0
	
	countdown() {
		
		local i 
		echo -n $1
		sleep 1
		for ((i=$1-1; i>=1; i--)); do
			printf "\b%d" $i
			sleep 1
		done
		printf "\b\b\b\bnow..."
	
	}
	
	
	joggleroff() {
		
		echo -n "Powering down in "
		countdown 9
		echo
		rm -rf /var/log/*
		sync
		[ ! -e $IMGLOC/test ] && shutdown -h now
		echo "System closed down."
		exit 0
		
	}
		
		
	checkimg() {
		
		local i="$1"
		if [[ -f "$i" ]]; then
		
			echo -n "Checking integrity of image..."
			CHECKSUM=`md5sum $i | awk -F\  '{print $1}'`
			if [ "$CHECKSUM" == "$IMGSUM" ]; then
				echo " successful."
				return 0
			else
				echo " checksum mismatch."
				return 1
			fi
		
		else
			
			echo "Image file does not exist."
			echo
			return 1
			
		fi
		
	}
	
	
	checkflash() {
				
		echo -n "Checking flash memory..."
		if [[ -e /dev/mmcblk0p1 ]] && [[ -e /dev/mmcblk0p2 ]] && [[ -e /dev/mmcblk0p3 ]] && [[ -e /dev/mmcblk0p4 ]]; then
			echo " successful."
			echo
		elif [[ -e /dev/mmcblk0 ]]; then
			echo " repartitioning required."
			echo
		else
			echo " failed."
			echo
			echo "Internal memory does not seem to exist."
			echo
			echo "This Joggler does not appear to have working internal flash memory."
			echo
			echo "You may have a faulty internal flash memory chip. You will still be able to boot this Joggler"
			echo "from USB devices, but it is uncertain whether you will be able to use the original operating"
			echo "system. Visit the Joggler Forums (http://www.jogglerwiki.com/forums) for help."
			echo
			joggleroff
		fi
		
	}
	
	
	nvramzap() {
		
		echo -n "Resetting NVRAM..."
		mount -o ro /dev/mmcblk0p2 /mnt
		/mnt/sbin/nvram -i &>/dev/null
		/mnt/sbin/nvram -w net.ntpenabled=YES &>/dev/null
		/mnt/sbin/nvram -w net.firsttime=No &>/dev/null
		/mnt/sbin/nvram -w net.priNTP=ntp2a.mcc.ac.uk &>/dev/null
		/mnt/sbin/nvram -w net.secNTP=ntp2b.mcc.ac.uk &>/dev/null
		sleep 1
		umount /mnt
		echo " done."
		
	}
	
	
	fetchimg() {
		
		counter=60
		echo
		echo -n "Stalling for network (up to $counter seconds)..."
			
		until ping -c 1 $SVR &>/dev/null
		do
			[ $counter -eq 0 ] && break
			sleep 1;
			let counter-=1
		done
		
		if [ $counter -eq 0 ]; then
			echo " not available."
			echo
			echo
			echo "Unable to connect to the O2 firmware server at OpenPeak."
			echo
			echo
			echo "==============================================================================================="
			echo
			echo "If this is the first time you have seen this message and you have a WIRED network connection"
			echo "with internet access attached to this Joggler, please power off and try again."
			echo
			echo "If you you have no wired network connection, you will need to download the firmware image from"
			echo "OpenPeak and add it to the 'reflash' directory of linux-boot before starting your Joggler."
			echo "Please read the documentation for details on how to do this."
			echo			
			echo "If you have seen this message before, the Joggler may not be receiving an IP address via DHCP."
			echo "Please download the image file manually and copy it into the 'reflash' directory."
			echo
			echo "==============================================================================================="
			echo
			echo
			sleep 20
			joggleroff
		else	
			echo " network ready."
			ntpdate ntp2a.mcc.ac.uk ntp2b.mcc.ac.uk ntp2c.mcc.ac.uk ntp2d.mcc.ac.uk 2>&1 >/dev/null
			echo "Downloading image..."
			echo
			echo
			echo "----------------------------------------------------------------------------------------------------"
			echo
			wget -O $IMGLOC/$IMG $URL$IMG
			sync
			echo "----------------------------------------------------------------------------------------------------"
			echo
			echo
		fi
		
	}
	
	
	reflash() {
		
		echo
		tput setaf 6
		echo "   --------------------------------------------------"
		echo "    WARNING: O2 JOGGLER REFLASHING IS ABOUT TO BEGIN "
		echo "   --------------------------------------------------"
		tput sgr0
		echo
		echo "Reflashing will permanently erase all files and restore this O2 Joggler to factory defaults."
		echo "To stop this, turn off the power to this device before the countdown ends."
		echo
		sleep 5
		echo -n "Reflash will begin in "
		countdown 9
		echo
		echo
		
		if [ "$1" == "repartition" ]; then
			echo -n "Recreating partition layout..."
			parted -s /dev/mmcblk0 mklabel msdos
			dd if=$RFCOMP/partitioning/mmcblk0.mbr of=/dev/mmcblk0 &>/dev/null
			sfdisk /dev/mmcblk0 < $RFCOMP/partitioning/mmcblk0.sf &>/dev/null
			echo " complete."
			sleep 2
			if [[ ! -e /dev/mmcblk0p1 ]] || [[ ! -e /dev/mmcblk0p2 ]] || [[ ! -e /dev/mmcblk0p3 ]] || [[ ! -e /dev/mmcblk0p4 ]]; then
				echo
				echo "Repartitioning has failed."
				echo				
				echo "You may have a faulty internal flash memory chip. You will still be able to boot this Joggler"
				echo "from USB devices, but it is uncertain whether you will be able to use the original operating"
				echo "system. Visit the Joggler Forums (http://www.jogglerwiki.com/forums) for help."
				echo
				joggleroff
			fi
		fi
		
		echo -n "Decompressing image..."
		rm -rf $RFCOMP/data &>/dev/null
		mkdir -p $RFCOMP/data
		tar mzxf $IMGLOC/$IMG -C $RFCOMP/data
		echo " done."
		echo
		
		echo "Reflashing system partition 1 of 2..."
		echo "----------------------------------------------------------------------------------------------------"
		[ ! -e $IMGLOC/test ] && $RFCOMP/data/tools/bin/partimage -z2 restore /dev/mmcblk0p2 $RFCOMP/data/payload/image.myg
		echo "----------------------------------------------------------------------------------------------------"
		echo
		
		echo "Reflashing system partition 2 of 2..."
		echo "----------------------------------------------------------------------------------------------------"
		[ ! -e $IMGLOC/test ] && $RFCOMP/data/tools/bin/partimage -z2 restore /dev/mmcblk0p3 $RFCOMP/data/payload/image.myg
		echo "----------------------------------------------------------------------------------------------------"
		echo
		
		echo "Restoring user partition..."
		echo "----------------------------------------------------------------------------------------------------"
		[ ! -e $IMGLOC/test ] && $RFCOMP/data/tools/bin/partimage -z1 restore /dev/mmcblk0p4 $RFCOMP/p1p4/mmcblk0p4.partimg.gz
		echo "----------------------------------------------------------------------------------------------------"
		echo
		
		echo -n "Restoring boot partition..."
		[ ! -e $IMGLOC/test ] && gzip -dc $RFCOMP/p1p4/mmcblk0p1.img.gz | dd of=/dev/mmcblk0p1 bs=1M
		echo " done."
		
		[ ! -e $IMGLOC/test ] && nvramzap
		
		echo
		echo
		tput setaf 6
		echo "   ---------------------"
		echo "    REFLASHING COMPLETE "
		echo "   ---------------------"
		tput sgr0
		echo
		echo		
		echo "This O2 Joggler is about to shut down. When shutdown is complete, turn off the power and"
		echo "disconnect the reflash USB device. Restore the power and allow the Joggler to boot."
		echo
		echo "NOTE: The first boot may take anything up to FIVE MINUTES to complete. Please be patient."
		echo
		
	}




## Use those subroutines!	
		
	FLASHCONDITION=$(checkflash)
	echo "$FLASHCONDITION"

	if [ -e $IMGLOC/repart ]; then
		FLASHCONDITION=repartition
		echo "Repartitioning has been requested."
		echo
	fi
	
	[ -e $IMGLOC/$IMG ] || fetchimg
	
	if [ -e $IMGLOC/$IMG ]; then
			
		if ( checkimg $IMGLOC/$IMG ); then
		
			if [[ "$FLASHCONDITION" =~ "successful" ]]; then
				reflash
				sleep 10
				joggleroff
			elif [[ "$FLASHCONDITION" =~ "repartition" ]]; then
				reflash repartition
				sleep 10
				joggleroff
			fi
	
		else
			
			rm $IMGLOC/$IMG
			echo
			echo "Unable to use the detected image. The faulty image file has been removed."
			echo
			echo
			echo "==============================================================================================="
			echo
			echo "If this is the first time you have seen this message, please power off and try again."
			echo
			echo "If you copied the image file to the USB device manually, please make sure that the image was"
			echo "not opened, modified or renamed on your system before being added to the device."
			echo
			echo "If you have seen this message before, there may be a fault with your USB device or problems"
			echo "fetching the image file. You might like to try again using another USB device, or downloading"
			echo "the image file manually and copying it into the 'reflash' directory."
			echo
			echo "==============================================================================================="
			echo
			echo
			sleep 20
			joggleroff
		
		fi
		
	else
		
		echo
		echo "Unable detect image file."
		echo
		echo
		echo "==============================================================================================="
		echo
		echo "If this is the first time you have seen this message, please power off and try again."
		echo
		echo "If you copied the image file to the USB device manually, please make sure that the image was"
		echo "not opened, modified or renamed on your system before being added to the device."
		echo
		echo "If you have seen this message before, there may be a fault with your USB device or problems"
		echo "fetching the image file. You might like to try again using another USB device, or downloading"
		echo "the image file manually and copying it into the 'reflash' directory."
		echo
		echo "==============================================================================================="
		echo
		echo
		sleep 20
		joggleroff
		
	fi
		
			
	;;
  stop|restart|force-reload)
	# Nothing to do here.
	;;
  *)
	echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac

:
