#!/bin/sh -x
set -e
# Check if we can do it
echo Checking environment
if [ "$(whoami)" != "root" ]; then
	echo You must run this script as root
	exit 0
fi

if [ "$(cat /proc/device-tree/banner-name | grep 'OLPC 4')" != "" ]; then
	XO=xo4
elif [ "$(cat /proc/device-tree/banner-name | grep 'OLPC 1')" != "" ]; then
	XO=xo175
else
	echo This script will only run on an ARM XO laptop
	exit 0
fi

. /etc/os-release
if [ "$PRETTY_NAME" != "Fedora 18 (Spherical Cow)" ]; then
	echo You need to be running a 13.2.0 build
	exit 0
fi

if [ -d /bootpart/boot/alt ]; then 
	echo You already have an alternative OS
	echo Will not install FatDog-ARM_XO
	exit 0
fi

if [ ! -f fd-arm.sfs ]; then
	echo Downloading the fd-arm.sfs file
	wget -c http://ftp.nluug.nl/ibiblio/distributions/fatdog/arm/releases/beta1/fd-arm.sfs
	sync
fi

echo Checking fd-arm.sfs integrity
if [ "$(md5sum fd-arm.sfs | cut -f1 -d ' ')" != "60e74a82d899f0324658b00319ff1ee9" ]; then
	echo Please re-download  the fd-arm.sfs file
	echo It is corrupted and deleted
	rm -f fd-arm.sfs
	exit 0
fi

echo Installing SFS ...
mkdir -p DEV
[ "$XO" = "xo4" ] && mount /dev/disk/mmc/mmc1p2 DEV/
[ "$XO" = "xo175" ] && mount /dev/disk/mmc/mmc2p2 DEV/
rm -f DEV/fd-arm.sfs
mv fd-arm.sfs DEV/
sync
umount DEV
rm -rf DEV

echo Getting the kernel and initrd
if [ ! -f "$XO"-kernel.tar.gz ]; then
	echo Downloading the "$XO" kernel
	wget -c http://ftp.nluug.nl/ibiblio/distributions/fatdog/arm/releases/beta1/"$XO"-kernel.tar.gz
	sync
fi
mkdir -p /bootpart/boot/alt
tar -C /bootpart/boot/alt/ -xf "$XO"-kernel.tar.gz --strip-components 2 "$XO"/boot/vmlinuz.* 
tar -C /bootpart/boot/alt/ -xf "$XO"-kernel.tar.gz --strip-components 2 "$XO"/boot/initrd.*
mv /bootpart/boot/alt/vmlinuz.* /bootpart/boot/alt/vmlinuz
mv /bootpart/boot/alt/initrd.* /bootpart/boot/alt/initrd.img
sync

for B in /bootpart/boot /boot  
do
sed '/ramdisk/ 	a\
	alternate?  if\
	visible\
	" basesfs=device:mmcblk0p2:\/fd-arm.sfs"  to boot-file\
	then' $B/olpc.fth > $B/olpc.fth.new
mv $B/olpc.fth $B/olpc.fth.orig
mv $B/olpc.fth.new $B/olpc.fth
done
echo
echo Done!
echo Restart your XO holding the \"O\" gamekey
echo to boot FatDog-ARM
