#!/bin/sh

BASE_URL=http://mirror.voyage.hk/download/voyage-mubox
URL_MUBOX=$BASE_URL/voyage-mubox-current.tar.xz
URL_CUBIE_BOOT=$BASE_URL/cubieboard2/boot-cubieboard2-latest.tar.xz
URL_CUBIE_KERNEL=$BASE_URL/cubieboard2/kernel-cubieboard2-latest.tar.xz

if [ -z "$1" ] ; then
	echo "Usage: $(basename $0) <install flash dev>"
	exit 1
fi

if [ ! -b "$1" ] ; then
	echo "$1 is not a disk device"
	exit 1
fi 

card=$1
mntpt=/tmp/cf

if [ ! -d "$mntpt" ] ; then mkdir -p $mntpt; fi

checkCmd()
{
	CMD=`which $1`
	if [ -z "$CMD" ] ; then
		echo "Command $1 not found!  Please install it first."
		exit 1
	fi
}

formatCard()
{
# cleaning
dd if=/dev/zero of=${card} bs=1024 seek=544 count=128

# formatting
dd if=/dev/zero of=$card bs=1M count=1

# partition starting at 2048th sector
[ -b $card ] && fdisk -u $card <<EOF
o
n
p
1
2048

p
w
EOF

# create ext4 filesystem, no mount check and assign volume label
mkfs.ext4 ${card}1
tune2fs -i 0 -c 0 ${card}1 -L voyage-mubox -O ^has_journal
}

#
# Install Root 
#  $1 - install tarball URL
#
installRoot()
{
	mount ${card}1 ${mntpt}
	curl $1 | tar --numeric-owner -Jxf - -C ${mntpt}
	umount ${mntpt}
}

installMBR()
{
	mount ${card}1 ${mntpt}
	dd if=${mntpt}/boot/sunxi-spl.bin of=$card bs=1024 seek=8
	dd if=${mntpt}/boot/u-boot.bin    of=$card bs=1024 seek=32
	umount ${mntpt}
	sync
}

checkCmd dd
checkCmd tar
checkCmd xz
checkCmd mount
checkCmd umount
checkCmd sync
checkCmd fdisk
checkCmd curl
checkCmd mkfs.ext4
checkCmd tune2fs

formatCard
installRoot $URL_MUBOX
installRoot $URL_CUBIE_BOOT
installMBR
installRoot $URL_CUBIE_KERNEL
sleep 5
echo "Voyage MuBox for Cubieboard2 installed!"

