#!/bin/bash

DISCOCFG=/etc/disco
if [ "$NOOP" != "" ]; then
    DISCOROOT=/var/disco/testfs/noop
else
    DISCOROOT=/var/disco/testfs/real
fi


mount | grep $DISCOROOT >/dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "disco chroot is already mounted, please exec disco-fs-unmount and try again."
    exit 1
fi

if [ $(cat ${DISCOROOT}/inited || echo 0) -ne 1 ]; then
    echo "disco chroot is not initialized, cannot be mounted. Please exec disco-fs-init and try again."
    exit 1
fi

# Mount all the (real filesystem) layers individually

mount --bind -o ro / ${DISCOROOT}/rootfs 2>&1 | grep -v "seems to be mounted read-write"
mount -o remount,ro ${DISCOROOT}/rootfs

# Setup filesystem layers. The read/write ones go on the top, with scratchfs ALWAYS on top.
# We even need the scratchfs in non-noop mode so we can generate the diff output, then rsync
# everything back onto the real filesystem.
FSLAYERS="${DISCOROOT}/scratchfs=rw"
if [ "$NOOP" != "" ]; then
    FSLAYERS="${FSLAYERS}:${DISCOROOT}/restricted=ro"
    FSLAYERS="${FSLAYERS}:${DISCOROOT}/munge=ro"
fi
FSLAYERS="${FSLAYERS}:${DISCOROOT}/dev=rw"
FSLAYERS="${FSLAYERS}:${DISCOROOT}/rootfs=ro"

# Union
unionfs -o cow,dev,dirs=$FSLAYERS ${DISCOROOT}/chroot

# Duplicate /proc and /sys if they already exist
# We have to do this here instead of layering them in the unionfs
# (or just letting unionfs duplicate them entirely) because there is
# some kind of checking that goes on in certain apps (like ps), that makes them
# think /proc is not mounted when it actually is, if we don't do this.

mount | grep " on /proc" >/dev/null 2>&1
if [ $? -eq 0 ]; then
    mount -t proc -o ro none ${DISCOROOT}/chroot/proc
fi
mount | grep " on /sys" >/dev/null 2>&1
if [ $? -eq 0 ]; then
    mount -t sysfs -o ro none ${DISCOROOT}/chroot/sys
fi

exit 0
