#! /bin/bash
#
# docomomo
#
# chkconfig: 2345 05 95
# description: mounts file systems from images in USB memory
#
# Copyright (C) 2006 zunda <zunda at freeshell.org>
# 
# Permission is granted for copying, modification, distribution,
# and distribution of modified versions of this work under the
# terms of GPL version 2. Read the GPL file for more details.
#

RETVAL=0

# Source function library.
. /etc/init.d/functions

# Functions
# loads kernel modules to mount USB storage
load_module() {
	echo $"Loading kernel modules for USB storage ..."
	modprobe scsi_mod
	modprobe usb-storage
	echo $"Waiting 8 seconds for drive initialization ..."
	sleep 8
	modprobe uhci-hcd
	modprobe fat
	modprobe vfat
}

# detects where the USB storage is
usb_disk() {
	dmesg | grep 'Attached scsi removable disk' | sed -n 's/.* //;$p'
}

# See how we were called.
case "$1" in

  start)
	# check kernel modules
	[ -z `usb_disk` ] && load_module
	usbdev=/dev/`usb_disk`1
	# mount file systems
	echo $"Mounting /usr and /home ..."
	(grep -q /mnt/usb /proc/mounts ||\
	 mount $usbdev /mnt/usb) && \
	(grep -q /usr /proc/mounts ||\
	 mount -t squashfs -o loop /mnt/usb/boot/usr.sqs /usr) && \
	(grep -q /home /proc/mounts ||\
	 mount -t ext2 -o loop /mnt/usb/boot/home.ext /home)
	RETVAL=$?
	# restore the modified files
	if [ -e /mnt/usb/boot/etc.tgz ]; then
		echo -n $"Restoring modified files in /etc:"
		(cd /etc; tar -z -x -v -f /mnt/usb/boot/etc.tgz)
	fi
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/docomomo
	;;

  stop)
	# store the modified files - this does not detect file deletion
	echo $"Storing modified files in /etc"
	find /etc -type f -newer /etc/.initrd.timestamp |\
	egrep -v '^(/etc/mtab|/etc/blkid|/etc/lvm|/etc/sysconfig/hwconf|/etc/sysconfig/xinit-session)' |\
 	sed 's/^\/etc\///' |\
	(cd /etc; xargs -r tar -z -v -c -f /mnt/usb/boot/etc.tgz)
	# umount file systems
	echo $"Processes still using /usr or /home ..."
	/sbin/fuser -k -c -v /usr /home && sleep 1 && \
	/sbin/fuser -k -c -v /usr /home && sleep 2
	echo -n $"Umounting /home, /usr, and the usb memory:"
	(grep -q /home /proc/mounts && umount /home) && \
	(grep -q /usr /proc/mounts && umount /usr) && \
	(grep -q /mnt/usb /proc/mounts && umount /mnt/usb)
	RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/docomomo
	;;

  status)
	if [ -e /var/lock/subsys/docomomo ]; then
		echo 'Modified files in /etc:'
		find /etc -type f -newer /etc/.initrd.timestamp |\
		egrep -v '^(/etc/mtab|/etc/blkid|/etc/lvm|/etc/sysconfig/hwconf|/etc/sysconfig/xinit-session)'
	fi

	;;
  *)
	echo $"Usage: $0 {start|stop|restart|reload|status}"
	exit 1
	;;
esac

exit $RETVAL 
