#!/bin/sh -e

case $1 in
  prereqs)
    exit 0
    ;;
esac

for x in $(cat /proc/cmdline); do
  case $x in
    root=*)
      ROOTNAME=${x#root=}
      ;;
    aufs=*)
      UNION=${x#aufs=}
        case $UNION in
          LABEL=*)
            RWLABEL=${UNION#LABEL=}
            UNION="/dev/disk/by-label/${UNION#LABEL=}"
            ;;
          UUID=*)
            UNION="/dev/disk/by-uuid/${UNION#UUID=}"
            ;;
        esac    
      ;;
  esac
done

if [ -z "$UNION" ]; then
    exit 0
fi

echo "Union: rw LABEL -> ${RWLABEL}"
echo "Union: root mount -> ${rootmnt}"

# make the mount points on the init root file system
mkdir /aufs /ro /rw

echo "* Union: mounting the rw filesystem."
if [ "$UNION" = "tmpfs" ]; then
  mount -t tmpfs rw /rw -o noatime,mode=0755
else
  mount ${rootmnt}/$UNION /rw -o noatime
fi

echo "* Union: moving the root out of the way"
mount --move ${rootmnt} /ro

echo "* Union: instantiating the union."
mount -t aufs aufs /aufs -o noatime,dirs=/rw:/ro=ro

# test for mount points on union file system
[ -d /aufs/ro ] || mkdir /aufs/ro
[ -d /aufs/rw ] || mkdir /aufs/rw

echo "* Union: moving partitions to /root /ro /rw."
mount --move /ro /aufs/ro
mount --move /rw /aufs/rw

# strip fstab off of root partition
grep -v $ROOTNAME /aufs/ro/etc/fstab > /aufs/etc/fstab

mount --move /aufs /root

exit 0
