### rootfsinstall: create partitions and fileysytems
#
# Based on rpi-install by: Davide Madrisan
# Modified by: Silvan Calarco <silvan.calarco@mambasoft.it>
#
SYSTEMFSTYPE=ext4

function usage() {
   echo "Usage: $0 device rootfs-archive [-y] [-rpi] [-fs fstype]"
   echo
   echo "Options:"
   echo "-fs   filesystem type for system partition (default: ext4)"
   echo "-rpi  make a RaspberryPi SD with boot partition"
   echo "-y    assume yes to all questions (script mode)"
   echo
   echo "Example: $0 /dev/sdb /tmp/openmamba-rootfs-light.arm.tar.xz"
   exit 1
}

[ $UID -eq 0 ] || {
   echo "ERROR: this script must be called as root; aborting."
   exit 1
}

while [ "$1" ]; do
   case $1 in
      -y) ASSUMEYES=1 ;;
      -rpi) RPIMODE=1 ;;
      -fs) [ $2 ] || {
              echo "Error: -fs option requires an argument; aborting."
              exit 1
           }
           SYSTEMFSTYPE=$2
           shift
           ;;
      -*) echo "Error: invalid option $1; aborting."
          exit 1
          ;;
       *) if [ ! "$DRIVE" ]; then
             DRIVE=$1
          elif [ ! "$ROOTFSARCHIVE" ]; then
             ROOTFSARCHIVE=$1
          else
             echo "Error: invalid argument $1; aborting."
             exit 1
          fi
          ;;
    esac
    shift
done
[ "$ROOTFSARCHIVE" ] || { usage; exit 1; }

if [ "${DRIVE:0:11}" = "/dev/mmcblk" ]; then
   PARTITION1=${DRIVE}p1
   PARTITION2=${DRIVE}p2
else
   PARTITION1=${DRIVE}1
   PARTITION2=${DRIVE}2
fi

# FIXME: in non rpi mode we only have system partition
[ "$RPIMODE" ] || PARTITION2=$PARTITION1

[ "$ASSUMEYES" ] || {
   echo -n "All current data in ${DRIVE} will be lost, do you want to proceed [y/N]?"
   read ans
   [ "$ans" = "y" -o "$ans" = "Y" ] || exit 0
}

sudo parted -s ${DRIVE} mktable msdos
if [ "$?" != "0" ]; then
   echo "ERROR: parted exited with error $? while creating partition table on ${DRIVE}; aborting."
fi

if [ "$RPIMODE" ]; then
   # FAT partition
   sudo parted -s -a cyl -- ${DRIVE} mkpart primary fat32 0 40M
   if [ "$?" != "0" ]; then
      echo "ERROR: parted exited with error $? while creating boot partition on ${DRIVE}; aborting."
   fi
   # rootfs partition
   sudo parted -s -a cyl -- ${DRIVE} mkpart primary $SYSTEMFSTYPE 40M -1
   if [ "$?" != "0" ]; then
      echo "ERROR: parted exited with error $? while creating system partition on ${DRIVE}; aborting."
   fi
else
   # rootfs partition
   sudo parted -s -a cyl -- ${DRIVE} mkpart primary $SYSTEMFSTYPE 0 -1
   if [ "$?" != "0" ]; then
      echo "ERROR: parted exited with error $? while creating system partition on ${DRIVE}; aborting."
   fi
fi

if [ "$RPIMODE" ]; then
   echo "Formatting $PARTITION1 (vfat) ..."
   mkfs.vfat -s 1 -F 32 -n "BOOT" $PARTITION1 || {
      echo "ERROR: unable to format $PARTITION1; aborting."
      exit 1
   }
fi

echo "Formatting $PARTITION2 ($SYSTEMFSTYPE)..."
mke2fs -q -t $SYSTEMFSTYPE -j -L "openmamba" $PARTITION2 || {
   echo "ERROR: unable to format $PARTITION2; aborting."
   exit 1
}

BOOTMP=`mktemp -d -t rootfsinstall.XXXXXXXX`
ROOTMP=`mktemp -d -t rootfsinstall.XXXXXXXX`

[ -d $BOOTMP -a -d $ROOTMP ] || {
   echo "Error: unable to create temporary mount points; aborting."
   exit 1
}

mount $PARTITION2 $ROOTMP || {
   echo "ERROR: unable to mount partition $PARTITION2; aborting."
   exit 1
}

if [ "$RPIMODE" ]; then
   ### SD-Card: install software

   echo "Fetching firmware from git..."
   SWHOME=`mktemp -d`

   cd $SWHOME
   git clone git://github.com/raspberrypi/firmware.git --depth=1

   mount $PARTITION1 $BOOTMP || {
      echo "ERROR: unable to mount partition $PARTITION1; aborting."
      exit 1
   }

   # bootcode.bin: 2nd stage bootloader, starts with SDRAM disabled
   # loader.bin  : 3rd stage bootloader, starts with SDRAM enabled
   # start.elf   : The GPU binary firmware image, provided by the foundation
   # kernel.img  : The OS kernel to load on the ARM processor.
   for f in bootcode.bin fixup_x.dat kernel.img start_x.elf LICENCE.broadcom; do
      cp $SWHOME/firmware/boot/$f $BOOTMP/
   done

   # cmdline.txt : parameters passed to the kernel on boot
   echo "\
dwc_otg.lpm_enable=0 \
root=/dev/mmcblk0p2 \
rootfstype=$SYSTEMFSTYPE \
quiet \
rootwait \
splash" > $BOOTMP/cmdline.txt

   # Create the kernel configuration file
   echo "\
arm_freq=800
force_turbo=1
gpu_mem=100
disable_overscan=1
start_file=start_x.elf
fixup_file=fixup_x.dat
framebuffer_depth=32
framebuffer_ignore_alpha=1" > $BOOTMP/config.txt

   ## Enable HDMI mode rather than DVI, if required
   #echo "\
   #hdmi_drive=2" >> $BOOTMP/config.txt

   # optional files:
   #   config.txt    : A configuration file read by the GPU.
   #                   Use this to override set the video mode, alter system clock
   #                   speeds, voltages, etc.
   #   vlls directory: Additional GPU code, e.g. extra codecs. 
   #                   Not present in the initial release.

   # copy kernel modules
   mkdir -p $ROOTMP/lib/modules
   cp -a $SWHOME/firmware/modules/* $ROOTMP/lib/modules/
   umount $PARTITION1
   rmdir $BOOTMP
   [ "$SWHOME" -a "${SWHOME:0:4}" = "/tmp" ] && rm -rf $SWHOME

fi # rpimode

pushd $ROOTMP >/dev/null || {
   echo "ERROR: unable to access system partition mount point; aborting."
   umount $PARTITION2
   rmdir $ROOTMP
   exit 1
}

echo "Uncompressing $ROOTFSARCHIVE..."
echo "This can take a while, please wait..."
tar xf $ROOTFSARCHIVE
popd >/dev/null

sync
umount $PARTITION2
rmdir $ROOTMP

echo "Done."
exit 0
