#!/bin/sh

set -e

export R="sudo"

## example values
export F="mer-armel-smartq5-rootfs-v0.16testing6.tar.gz"
export D="/dev/sdi2"
export DF="/dev/sdi1"
export V="/dev/sdi"
export M="/mnt/tmp"

echo ""
echo "=========================================================="
echo "Get Mer updates from:"
echo "  http://wiki.maemo.org/Mer/Releases/0.16testing"
echo "Get QI from:"
echo "  http://zenvoid.org/software/qi-smartq/"
echo "Get firmware from:"
echo "  http://www.marvell.com/drivers/driverDisplay.do?driverId=203"
echo "=========================================================="
echo ""

if [ $# -lt 4 ]; then
  echo "usage: mer-img.sh ROOTFS-TO-INSTALL DEVICE PARTITION MOUNT"
  echo ""
  echo "e.g.:"
  echo "mer-img.sh mer-armel-smartq5-rootfs-v0.16testing6.tar.gz /dev/sdi /dev/sdi2 /dev/sdi1 /media/tmp"
  exit 1
fi

F=$1
V=$2
D=$3
DF=$4
M=$5

if [ ! -d qi ]; then
  mkdir qi
  pushd qi >& /dev/null
  wget http://zenvoid.org/software/qi-smartq/qi-smartq-20090612.tar.bz2
  wget http://zenvoid.org/software/qi-smartq/qi-smartq-20090612.bin
  wget http://zenvoid.org/software/qi-smartq/install-smartq-qi.sh
  popd >& /dev/null
fi

if [ ! -d fw ]; then
  mkdir fw
  pushd fw >& /dev/null
  firefox "http://www.marvell.com/drivers/driverDisplay.do?driverId=203"
  popd >& /dev/null
fi

echo "Creating mount point $M"
$R mkdir $M

echo "Formatting FAT"
$R mkfs.vfat $DF -n FAT
echo "Mounting $DF at $M"
$R mount $DF $M
echo "Adding firmware for Wifi"
$R cp fw/SD-8686-LINUX26-SYSKT-9.70.3.p24-26409.P45-GPL.zip $M/
echo "Syncing to disk"
sync
echo "Unmounting $M"
$R umount $M

echo "Formatting Root"
$R mkfs.ext3 $D -L Mer-Root
$R tune2fs -c 0 $D
echo "Mounting $D at $M"
$R mount $D $M
echo "Clearing Rootfs"
pushd $M >& /dev/null
$R rm -rf .* *  >& /dev/null || true
popd >& /dev/null
echo "Untarring new Mer Rootfs"
$R tar --numeric-owner -zxf $F -C $M

echo "Fixing qi boot name for kernel"
$R cp $M/boot/zImage* $M/boot/linux-SMDK6410.bin
echo "Disabling ondemand scheduler init"
$R rm $M/etc/rc2.d/*ondemand || true
$R rm $M/etc/rc3.d/*ondemand || true
$R rm $M/etc/rc4.d/*ondemand || true
$R rm $M/etc/rc5.d/*ondemand || true

echo "Syncing to disk"
sync
echo "Unmounting $M"
$R umount $M
echo "Removing mount point $M"
$R rmdir $M
echo "Installing QI onto $V"
$R ./qi/install-smartq-qi.sh $V ./qi/qi-smartq-20090612.bin
echo "Syncing disk"
sync
echo "Done."
echo ""
