#!/bin/sh

# if necessary mount iso image loopback
# use aufs to make iso image "writable"

# See manpage initramfs-tools(8)
[ -f /scripts/functions ] && . /scripts/functions

PREREQ=""
prereqs()
{
    echo "$PREREQ"
}

case $1 in
prereqs)
    prereqs
    exit 0
    ;;
esac

# chkerr <EXIT CODE> <action performed>
chkerr()
{
    e=$1
    shift 
    if [ $e -ne 0 ]; then
      echo "bootcdaufs: ERROR $e while running: $*"
      echo "try to fix and exit"
      /bin/sh
    fi
}

getiso()
{
  sed -n "s/^.*\<root=iso:\([^ :]*\):\([^ ]*\)\>.*$/\2/p"
}


if [ "$(grep "\<bootcd=" /proc/cmdline)" ]; then
    echo "bootcdaufs rootmnt=<$rootmnt>"

    iso="$(cat /proc/cmdline | getiso)"
    if [ "$iso" ]; then
      mkdir /bootcd.disk_with_iso
      mount --move ${rootmnt} /bootcd.disk_with_iso
      chkerr $? "mount --move ${rootmnt} /bootcd.disk_with_iso"

      modprobe loop
      mount -o loop -t iso9660 /bootcd.disk_with_iso/${iso} ${rootmnt}
      chkerr $? "mount -o loop -t iso9660 /bootcd.disk_with_iso/${iso} ${rootmnt}"
    fi

    mkdir /bootcd.aufs
    mount none -t tmpfs /bootcd.aufs
    chkerr $? "mount none -t tmpfs /bootcd.aufs"

    mkdir /bootcd.ro
    mount --move ${rootmnt} /bootcd.ro
    chkerr $? "mount --move ${rootmnt} /bootcd.ro"

    mkdir /aufs
    mount none -t aufs -o dirs=/bootcd.aufs:/bootcd.ro=ro /aufs
    chkerr $? "mount none -t aufs -o dirs=/bootcd.aufs:/bootcd.ro=ro /aufs"


    mkdir -p /aufs/mnt/bootcd.ro 
    mount --move /bootcd.ro /aufs/mnt/bootcd.ro
    chkerr $? "mount --move /bootcd /aufs/mnt/bootcd.ro"

    if [ "$iso" ]; then
      mkdir -p /aufs/mnt/bootcd.disk_with_iso
      mount --move /bootcd.disk_with_iso /aufs/mnt/bootcd.disk_with_iso
      chkerr $? "mount --move /bootcd.disk_with_iso /aufs/mnt/bootcd.disk_with_iso"
    fi

    mkdir -p /aufs/mnt/bootcd.aufs
    mount --move /bootcd.aufs /aufs/mnt/bootcd.aufs
    chkerr $? "mount --move /bootcd.aufs /aufs/mnt/bootcd.aufs"

    mount --move /aufs ${rootmnt}
    chkerr $? "mount --move /aufs ${rootmnt}"
fi

exit 0
