#!/bin/sh
#
# Must be run as root.
#
# version 1.8 as of 2011-03-17
#
# Released under the GPL
#
# This script should be run on the Touch Book itself
#
# This script install a new kernel on the first partition
# Then you need to reboot your Touch Book and press the advanced
# option when you see the multi-OS boot UI. You will then be offered
# various options including to reinstall the operating systems.

RELEASE=latest
BASEURL=http://build.alwaysinnovating.com/release/

if [ "m`id -u`" != "m0" ]; then
	echo "You must be root"
	exit 1
fi

/usr/bin/ai/networking/http_test.sh
if [ $? != 0 ]; then
	/usr/bin/zenity --info --title "Reinstallation" --text "Your device must be connected to the Internet. Please check your network settings and retry."
	exit 1
fi

on_error(){
	echo
	echo "An error occured. Please relaunch the script."
	echo
	exit 1
}

mount | grep -q "/dev/mmcblk0p1"
if [ $? = 0 ]; then
	trap on_error ERR
	umount /dev/mmcblk0p1
else
	trap on_error ERR
fi
VERSION=`cat /etc/ai.version`
if [ ${VERSION} \< "2011-03.a" ]; then
	wget -O /usr/sbin/mkdosfs http://www.alwaysinnovating.com/download/mkdosfs
fi
mkfs.vfat -F 32 /dev/mmcblk0p1
sync
mkdir -p /tmp/mnt1
mount /dev/mmcblk0p1 /tmp/mnt1
wget -O /tmp/mnt1/mlo ${BASEURL}${RELEASE}/mlo
umount /dev/mmcblk0p1
sync
mount /dev/mmcblk0p1 /tmp/mnt1
wget -O /tmp/mnt1/u-boot.bin ${BASEURL}${RELEASE}/u-boot.bin
wget -O /tmp/mnt1/uImage ${BASEURL}${RELEASE}/uImage
wget -O /tmp/mnt1/uImage2 ${BASEURL}${RELEASE}/uImage2
wget -O /tmp/mnt1/ai-install.tbz2 ${BASEURL}${RELEASE}/ai-install.tbz2
wget -O /tmp/mnt1/ai-ui.tbz2 ${BASEURL}${RELEASE}/ai-ui.tbz2
umount /tmp/mnt1

echo "You need now to reboot your Touch Book to continue the upgrade."
echo "You will need an internet connection (public or WEP only) or"
echo "You need to download the image archive on a USB keychain to be"
echo "inserted into the Touch Book during reboot."
echo "During reboot, press the power button multiple times, and then"
echo "select the advanced menu in the bottom left corner."
echo "Select the option #6 to reinstall the Touch Book."
echo "Note that all data will be erased during the reinstallation."
