#! /bin/bash
### BEGIN INIT INFO
# Provides:          casper-split
# Required-Start:    $syslog
# Required-Stop:
# Should-Start:      $local_fs
# Should-Stop:       halt reboot
# X-Stop-After:      umountroot
# Default-Start:
# Default-Stop:      0 6
# Short-Description: Casper init script
# Description:       Resyncs snapshots, evantually caches files in order
#                    to let remove the media.
### END INIT INFO

# Author: Tollef Fog Heen <tfheen@canonical.com>
#         Marco Amadori <marco.amadori@gmail.com>
#
PATH=/usr/sbin:/usr/bin:/sbin:/bin
NAME=casper-split
SCRIPTNAME=/etc/init.d/${NAME}

# Exit if system was not booted by casper
grep -qs boot=casper /proc/cmdline || exit 0

# Exit if the system was booted from an ISO image rather than a physical CD
#grep -qs find_iso= /proc/cmdline && exit 0

# Read configuration variable file if it is present
[ -r /etc/$NAME.conf ] && . /etc/$NAME.conf

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

case "$1" in
    restart|reload|force-reload|status)
        [ "$VERBOSE" != no ] && log_end_msg 0
        ;;
    # We normally run on start; stop is just for backwards compatibility.
    start)
        log_begin_msg "${NAME} is mounting additional squashfs files ..."
        SPLITFS=$(cd /cdrom/casper; find . -name "filesystem-*.squashfs-split")
        if [ -n "$SPLITFS" ]; then
          mkdir -p /cow.d
          for f in $SPLITFS; do
            if [ -r /cdrom/casper/$f ]; then 
              m=${f#./filesystem}
              m=${m%.squashfs-split}
              cow=/cow.d/$m
              mount -t ramfs none /cow.d/$m
              m=${m//-/\/}
              mkdir -p $cow
              mkdir -p $m
              
              mount -t squashfs -o loop,ro /cdrom/casper/$f $m
              mount -t aufs -o  dirs=$cow=rw:$m=ro aufs $m
            fi
          done
        fi
        case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
            2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
    *)
        log_success_msg "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
        exit 3
        ;;
esac
