#!/bin/sh

BASE_URL=http://mirror.voyage.hk/download/voyage-mubox
URL_MUBOX=$BASE_URL/voyage-mubox-current.tar.xz
URL_CUBOXI_BOOT=$BASE_URL/cubox-i/boot-cubox-i.tar.xz
URL_CUBOXI_KERNEL=$BASE_URL/cubox-i/kernel-cubox-i-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
mntpt1=/tmp/cf1

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

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

formatCard()
{
# 1 partition , 1 ext4, no journal
dd if=/dev/zero of=$card count=32768 count=64
[ -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 Boot
#  $1 - install tarball URL
#
installBoot()
{
	mount ${card}1 ${mntpt}
	curl $1 | tar --numeric-owner -Jxf - -C ${mntpt}/boot

	sync
	
	dd if=${mntpt}/boot/SPL of=${card} bs=512 seek=2
	dd if=${mntpt}/boot/u-boot.img of=${card} bs=1K seek=42
	sync

	umount ${mntpt}
	sync
}

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

postInstall()
{
        mount ${card}1 ${mntpt}
	sed -i -e "s/ttyS0/ttymxc0/" ${mntpt}/etc/inittab
	sed -i -e "/^options.*snd-usb-audio/s/^/#/" ${mntpt}/etc/modprobe.d/alsa-base.conf
	ln -sf boot/zImage ${mntpt}/zImage
	ln -sf boot/uEnv.txt ${mntpt}/uEnv.txt

	sync
        umount ${mntpt}
        sync
}


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

formatCard
installRoot $URL_MUBOX
installRoot $URL_CUBOXI_KERNEL
installBoot $URL_CUBOXI_BOOT
postInstall

sync
sleep 5
echo "Voyage MuBox for CuBox-i installed!"

