#!/bin/bash
# Live USB filesystem mounting			-*- shell-script -*-

mountroot ()
{
    CFG_FILE=/etc/moblin-initramfs.cfg
    if [ -f ${CFG_FILE} ]
    then
	. ${CFG_FILE}
    else
	echo "Did not find config file: ${CFG_FILE}"
	sleep 5
    fi
    mkdir -p /container
    mkdir -p /squashmnt
    mkdir -p /persistmnt

    # Find the USB flash drive
    while true
    do
      for device in 'sda' 'sdb' 'sdc' 'sdd'; do
        echo "checking device /dev/${device} for installation source..."
        if [ -e /sys/block/${device}/removable ]; then
           if [ "$(cat /sys/block/${device}/removable)" = "1" ]; then
              echo "Found USB flash drive at /dev/${device}"
	      found="yes"
              break
           fi
         fi
      done
      if [ "$found" = "yes" ]; then
	break;
      fi
      echo "Sleeping for 5 seconds"
      /bin/sleep 5
      echo "Sleeping finished"
    done
    echo "will mount root from /dev/${device}"

    mount -o rw /dev/${device} /container 2> /dev/null
    while [ ! -e "/container/rootfs.img" ]; do
	/bin/sleep 0.5
	mount -o rw /dev/${device} /container 2> /dev/null
    done

    mount -o ro,loop -t squashfs /container/rootfs.img /squashmnt

    if [ -f /container/ext3fs.img ]; then
        mount -o rw,loop,noatime,nodiratime /container/ext3fs.img /persistmnt
    else
        mount -t tmpfs -o noatime,nodiratime none /persistmnt
    fi

    mount -t unionfs -o dirs=/persistmnt=rw:/squashmnt=ro none ${rootmnt}

    if [ -f /container/install.sh ]; then
	 log_begin_msg "Install Process will begin shortly..."
	 maybe_break preinstall

	 mkdir -p ${rootmnt}/tmp/install
	 mount --bind /dev ${rootmnt}/dev
	 mount --bind /sys ${rootmnt}/sys
	 mount --bind /container ${rootmnt}/tmp/install
	 cp /container/install.sh ${rootmnt}
	 cp /container/install.cfg ${rootmnt}

	 maybe_break install
	 chroot ${rootmnt} /install.sh
    fi
}
