#!/bin/bash -e

# defaults
RELEASE="stable"
SERVER_URL="http://meshcube.org/nylon"
FLASH_KERNEL="yes"
FI_NAME="filesystem.img.gz"
KI_NAME="kernel.img.gz"
USE_LOCAL_PATH="no"

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

this script installs a completely new filesystem and kernel image

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

Optional arguments:
  -h			display this
  -n			do not flash a new kernel
  -s SERVER_URL		get images from this server url
			e.g.: "http://192.168.0.1/path/to/images/"
			(default: http://meshcube.org/nylon/unstable/images/)
  -f NAME		filesystem image name (default: filesystem.img.gz)
  -k NAME		kernel image name (default: kernel.img.gz)
  -l PATH		use local images from PATH (e.g.: "/tmp/uploaded" or "/mnt")
  -r RELEASE		use release "stable", "testing" or "unstable" (default: "stable")

UEOF
exit
}

# options
while getopts "hns:f:k:l:r:" options; do
	case $options in
		n ) FLASH_KERNEL="no";;
		s ) SERVER_URL=$OPTARG;;
		f ) FI_NAME=$OPTARG;;
		k ) KI_NAME=$OPTARG;;
		l ) USE_LOCAL_PATH=$OPTARG;;
		r ) RELEASE=$OPTARG;;
		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"

SERVER_URL_IMAGE="${SERVER_URL}/${FI_NAME}"
SERVER_URL_KERNEL="${SERVER_URL}/${KI_NAME}"

# warning #####################################
cat <<WARNEOF
*** INSTALL NEW FILESYSTEM 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 filesystem and kernel images
from a server, write them 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 IMAGES FROM:    "
if [ $USE_LOCAL_PATH == "no" ]; then
	echo "$SERVER_URL"
else
	echo "$USE_LOCAL_PATH"
fi
echo "FLASH_KERNEL:           $FLASH_KERNEL"
echo "FILESYSTEM IMAGE NAME:  $FI_NAME"
echo "KERNEL IMAGE NAME:      $KI_NAME"
echo

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

# 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 [ $USE_LOCAL_PATH == "no" ]; then
	echo "* downloading filesystem from ${SERVER_URL_IMAGE}"
	wget -O /tmp/root/${FI_NAME} ${SERVER_URL_IMAGE}
	echo "* uncompressing filesystem"
	gunzip /tmp/root/${FI_NAME}
	
	if [ $FLASH_KERNEL == "yes" ]; then
		echo "* downloading kernel from ${SERVER_URL_KERNEL}"
		wget -O /tmp/root/${KI_NAME} ${SERVER_URL_KERNEL}
		echo "* uncompressing kernel"
		gunzip /tmp/root/${KI_NAME}
	fi
else
	echo "* uncompressing local filesystem image"
	gunzip -c ${USE_LOCAL_PATH}/${FI_NAME} > /tmp/root/${FI_NAME%%.gz}
	if [ $FLASH_KERNEL == "yes" ]; then
		echo "* uncompressing local kernel image"
		gunzip -c ${USE_LOCAL_PATH}/${KI_NAME} > /tmp/root/${KI_NAME%%.gz}
	fi
fi

# check if images are there
test -s /tmp/root/${FI_NAME%%.gz} || { echo "* download of filesystem image failed!"; exit 1; }
if [[ $FLASH_KERNEL == "yes" ]]; then 
	test -s /tmp/root/${KI_NAME%%.gz} || { 
		echo "* download of kernel image failed!"; 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
# different path 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
cp /bin/busybox /tmp/root/bin
cp /bin/bash /tmp/root/bin
# different path on old release
if test -e /usr/bin/flashcp; then
	cp /usr/bin/flashcp /tmp/root/bin
else
	cp /usr/bin/fcp /tmp/root/bin/flashcp
fi
cp /sbin/halt /tmp/root/bin
ln -sfn halt /tmp/root/bin/reboot

# 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
if [ $FLASH_KERNEL == "yes" ]; then
	busybox echo "* installing new kernel... "
	flashcp -v ${KI_NAME%%.gz} /dev/mtd/2
fi

busybox echo "* installing new filesystem image... "
flashcp -v ${FI_NAME%%.gz} /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
