#
# 
# DESCRIPTION:
#
#    Prepare a root-filesystem under $ROOTPATH, 
#    use device mapper snapshot target as overlay filesystem.
#
#    This technique requires the system image to be a rw filesystem like
#    ext2/ext3. You could use squashfs to achieve compression
#    by embedding the ext2/3 filesystem into a squashfs filesystem. 
#
# part of the LiveBackup project:  
#
#                     http://livebackup.sourceforge.net/
#
# Copyright 2006-2010 by Wolfgang Rohrmoser <info@rohrmoser-engineering.de>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#


#
# the mounted image must now contain an $SYSTEM.ext2 
#

msg -i "using device mapper snapshot target for filesystem overlay"


#
# ensure we have the device mapper modules available
#
for mod in dm-snapshot; do 
    modprobe $mod
    if [ $? -ne 0 ]; then 
        msg -c "ERROR: missing $mod module"
        exit
    fi
done

#
# check for ext2 filesystem image
#
if [ ! -f $IMAGE_MNT/$SYSTEM.ext2 ]; then
    msg -c "ERROR: $IMAGE_MNT/$SYSTEM.ext2 not found"
    exit
fi

SYSTEM_LOOPDEV=/dev/loop1   # $( losetup -f )
OVERLAY_LOOPDEV=/dev/loop2  # $( losetup -f )

#
# assign a loop device to system image
#
losetup $SYSTEM_LOOPDEV $IMAGE_MNT/$SYSTEM.ext2

# make writable filesystem layer
execute mount_rwdisk $OVERLAY_MNT $LB_METHOD_OPT

# check for an overlay file
if [ ! -f $OVERLAY_MNT/$SYSTEM.ovl ]; then
    # create a sparse overlay file
    # !!! ToDo determine a suitable size !!! 
    size=32  # MB
    dd if=/dev/null of=$OVERLAY_MNT/$SYSTEM.ovl bs=1024 count=1 seek=$((size*1024)) 2>/dev/null
fi
losetup $OVERLAY_LOOPDEV $OVERLAY_MNT/$SYSTEM.ovl

#
# setup snapshot overlay
#
echo "0 $(blockdev --getsize $SYSTEM_LOOPDEV) snapshot $SYSTEM_LOOPDEV $OVERLAY_LOOPDEV p 8" | dmsetup create live-rw

#
# finally mount the rootfs
#
mount -n /dev/mapper/live-rw $ROOTPATH


#
# Local Variables: 
# mode: shell-script
# End: 
#


