#! /bin/bash
#
# docomomo
#
# chkconfig: 2345 03 97
# 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 or later.
#
# Read the GPL.txt fle or gpl-3.0.txt 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 -i 'Attached SCSI removable disk' | sed 's/.*\(sd[a-z]\).*/\1/;2Q'
}

usb_uuid() {
	for argv in $(cat /proc/cmdline); do
		case $argv in
			docomomo_uuid=*)
				echo ${argv#docomomo_uuid=}
				break
				;;
		esac
	done
}

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

  start)
	# check kernel modules
	[ -z `usb_disk` ] && load_module
	# mount file systems
	echo $"Mounting /usr and /home ..."
	uuid=`usb_uuid`
	(grep -q /mnt/usb /proc/mounts ||\
	 if [ -z "$uuid" ]; then mount /dev/`usb_disk`1 /mnt/usb; else mount -U $uuid /mnt/usb; fi) && \
	(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|status}"
	exit 1
	;;
esac

exit $RETVAL 
