#!/bin/sh

BASE_URL=http://mirror.voyage.hk/download/voyage-mubox
URL_MUBOX=$BASE_URL/voyage-mubox-current.tar.xz
URL_BBB_BOOT=$BASE_URL/beaglebone/boot-beaglebone.tar.xz
URL_BBB_KERNEL=$BASE_URL/beaglebone/kernel-beaglebone-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()
{
# 2 partition , 1 vfat and 1 ext4 w/o journal
[ -b $card ] && fdisk $card <<EOF
o
n
p
1

+64M
t
e
a
1
n
p
2


p
w
EOF

# create ext2 filesystem, no mount check and assign volume label
mkfs.vfat -F 16  ${card}1
mkfs.ext4 ${card}2
tune2fs -i 0 -c 0 ${card}2 -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}
	umount ${mntpt}
	sync
}

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

postInstall()
{
        mount ${card}2 ${mntpt}
	find ${mntpt}/lib/modules/ -name "*ko.gz" -exec gunzip '{}' ';'
	sed -i -e "s/ttyS0/ttyO0/" ${mntpt}/etc/inittab
	sed -i -e "/^options.*snd-usb-audio/s/^/#/" ${mntpt}/etc/modprobe.d/alsa-base.conf
        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
installBoot $URL_BBB_BOOT
installRoot $URL_MUBOX
installRoot $URL_BBB_KERNEL
postInstall

sync
sleep 5
echo "Voyage MuBox for BeagleBone (Black) installed!"

