#!/bin/bash -e

# defaults
SERVER_URL="http://meshcube.org/nylon"
IMG_NAME="nylon.imgz"
LOCAL_PATH="no"
RELEASE="stable"
KERNEL_IMG=""
ASK="yes"


# print usage
usage() {
cat <<UEOF
Usage: $0 [-h] [-r RELEASE] [-s SERVER_URL] [-l LOCAL_PATH] [-n IMAGE_NAME ]

this script installs a completely new nylon distribution image (aka "firmware")

it will download the nylon image from a server, write it to the flash 
and then reboot the cube.
WARNING: all custom modifications and configurations will be lost in this process!

Optional arguments:
  -h			display this
  -s SERVER_URL		get images from this server url
			e.g.: "http://192.168.0.1/path/to/images/"
			(default: http://meshcube.org/nylon/stable/images/)
  -n NAME		image name (default: "nylon.imgz")
  -l PATH		use local images from PATH (e.g.: "/tmp/uploaded" or "/mnt")
  -r RELEASE		use release "stable", "testing" or "unstable" (default: "stable")
  -k KERNEL_IMAGE	only flash kernel image
  -y			don't ask, just do it. non-interactive mode
UEOF
exit
}


# options
while getopts "n:s:l:r:k:yh" options; do
	case $options in
		n ) IMG_NAME=$OPTARG;;
		s ) SERVER_URL=$OPTARG;;
		l ) LOCAL_PATH=$OPTARG;;
		r ) RELEASE=$OPTARG;;
		k ) KERNEL_IMG=$OPTARG;;
	        y ) ASK="no";;
		h ) usage;;
		\?) usage;;
		* ) usage
	esac
done

[[ ${SERVER_URL:0:7} != "http://" && ${SERVER_URL:0:6} != "ftp://" ]] && SERVER_URL="http://$SERVER_URL"
[[ ${SERVER_URL} == "http://meshcube.org/nylon" ]] && SERVER_URL="${SERVER_URL}/${RELEASE}/images"


# only kernel: that's easy

if [ "x$KERNEL_IMG" != "x" ]; then
cat <<KERNEOF
*** INSTALL NEW KERNEL IMAGE ***

**************************************************************
*** !!! WARNING !!!                                        ***
*** updating the kernel only can cause inconsistencies     ***
*** with kernel modules.                                   ***
*** therefore it's recommeded to always install a complete ***
*** (*.imgz) image, unless you know what you are doing.    ***
**************************************************************

KERNEOF
	echo -n "GETTING IMAGE FROM:    "
	if [ $LOCAL_PATH == "no" ]; then
		echo "$SERVER_URL"
	else
		echo "$LOCAL_PATH"
	fi

	echo "IMAGE NAME:            $KERNEL_IMG"
	echo

	# ask
	if [ "x$ASK" == "xyes" ]; then
		read -p "*** do you really want to contine? (yes/no) " answer
		[ "x$answer" == "xyes" ] ||  exit 0;
	fi

	if [ $LOCAL_PATH == "no" ]; then
		echo "* downloading kernel image from ${SERVER_URL}"
		wget -O /tmp/${KERNEL_IMG} ${SERVER_URL}/${KERNEL_IMG}
		flashcp -v /tmp/${KERNEL_IMG} /dev/mtd/2
	else 
		echo "* using local kernel image ${LOCAL_PATH}/${KERNEL_IMG}"
		flashcp -v ${LOCAL_PATH}/${KERNEL_IMG} /dev/mtd/2
	fi
	echo "*** kernel flashed, please reboot ***"
	exit
fi


# normal case:

# warning #####################################
cat <<WARNEOF
*** INSTALL NEW NYLON IMAGE ***

**************************************************************
*** !!! WARNING !!!                                        ***
*** you will loose all your data!!!                        ***
*** if you continue you will loose all your configuration, ***
*** all files and other changes you made to your cube!     ***
***                                                        ***
*** do not power off the cube while flashing!!!            ***
**************************************************************

this script will download the nylon distribution image from a 
server, write it to the flash and then reboot the cube.
this process will take about 10 minutes after the download has
completed, and is not without risk. if the cube does not reboot
after 10 minutes, something went wrong and you may have to use
the serial cable to recover it.

use $0 -h to see command line options

WARNEOF
###############################################

# display settings
echo -n "GETTING IMAGE FROM:    "
if [ $LOCAL_PATH == "no" ]; then
	echo "$SERVER_URL"
else
	echo "$LOCAL_PATH"
fi
echo    "IMAGE NAME:            $IMG_NAME"
echo

# ask
if [ "x$ASK" == "xyes" ]; then
    read -p "*** do you really want to contine? (yes/no) " answer
    [ "x$answer" == "xyes" ] ||  exit 0;
fi

# go
echo 
echo "* remounting /tmp to fit new images"

mount -o remount,size=50M `mount|grep tmpfs|awk '{print $3}'`

rm -rf /tmp/root
mkdir -p /tmp/root

if [ $LOCAL_PATH == "no" ]; then
	echo "* downloading image from ${SERVER_URL}"
	wget -O /tmp/root/${IMG_NAME} ${SERVER_URL}/${IMG_NAME}
else
	echo "* copying image from ${LOCAL_PATH}"
	cp ${LOCAL_PATH}/${IMG_NAME} /tmp/root/${IMG_NAME}
fi

# test if download completed
if ! test -s /tmp/root/${IMG_NAME}; then
	echo "* download failed"
	exit 1;
fi

# verify the file contains what we need
if ! tar tzf /tmp/root/${IMG_NAME} zImage.flash rootfs.jffs2; then
	echo "* image corrupted or wrong file"
	exit 1;
fi

echo "* preparing flash environment (chroot)"
mkdir /tmp/root/lib
mkdir /tmp/root/bin
mkdir /tmp/root/dev
cp /lib/ld.so.* /tmp/root/lib
cp /lib/libc.so.* /tmp/root/lib
cp /lib/libm.so.* /tmp/root/lib
cp /lib/libcrypt.so.* /tmp/root/lib
cp /lib/libdl.so.* /tmp/root/lib
cp /bin/busybox /tmp/root/bin
cp /bin/bash /tmp/root/bin
cp /sbin/halt /tmp/root/bin
ln -sfn halt /tmp/root/bin/reboot
# different paths on old release
if test -e /usr/lib/libncurses.so.5; then
	cp /usr/lib/libncurses.so.* /tmp/root/lib
else
	cp /lib/libncurses.so.* /tmp/root/lib
fi
if test -e /usr/bin/flashcp; then
	cp /usr/bin/flashcp /tmp/root/bin
	cp /usr/bin/flash_eraseall /tmp/root/bin
else
	cp /usr/bin/fcp /tmp/root/bin/flashcp
fi
if test -e /usr/bin/flash_eraseall; then
	cp /usr/bin/flash_eraseall /tmp/root/bin
else
	cp /usr/bin/eraseall /tmp/root/bin/flash_eraseall
fi


# init script #################################
cat > /etc/rc1.d/S99image <<EOF
#!/bin/bash

echo "* killing all remaining processes"
killall5 -9
sleep 10

# remount / ro for another safety belt
mount -o remount,ro /

chroot /tmp/root /flash.sh

EOF
###############################################


# flash script ################################
cat > /tmp/root/flash.sh <<EOF2
#!/bin/bash

busybox mount -t devfs none /dev

# now copy images to flash
busybox echo "* installing new kernel... "
flash_eraseall /dev/mtd/2
busybox tar xzOf ${IMG_NAME} zImage.flash > /dev/mtd/2

busybox echo "* installing new filesystem image... "
flash_eraseall /dev/mtd/0
busybox tar xzOf ${IMG_NAME} rootfs.jffs2 > /dev/mtd/0

busybox echo "*** done. rebooting. ***"

reboot -f -n

EOF2
###############################################


chmod a+x /etc/rc1.d/S99image
chmod a+x /tmp/root/flash.sh

cat << ENDEOF
* switching to single user mode

**************************************************************
*** FLASHING IN PROGRESS                                   ***
***                                                        ***
*** !!!do not power off the cube in the next 10 minutes!!! ***
**************************************************************

if you are connected via ssh you will not see any output up from
this point. the flash process will continue nevertheless...

*** please wait approximatly 10 minutes until the cube reboots ***

afterwards you will be able to login with empty password to the
new system on

ethernet:    192.168.0.250
accesspoint: 10.0.0.1        essid cube-ap
mesh:        172.16.0.1      essid cube-mesh

ENDEOF

sleep 5

init 1
