#!/bin/sh
# COPYRIGHT (C) 2007 Zachary White <zwhite@darkstar.frop.org>
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation.
# 
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

### USER CHANGABLE SECTION
flashdevice=sda			# The device for our flash reader
mountpoint=/mnt/camera		# Where we're going to mount the flash
backuppoint=/mnt/sly/Pictures/	# Where to save a backup of the card

### END USER CHANGABLE SECTION

### IF YOU CHANGE ANYTHING BELOW, YOU GET WHAT YOU ASKED FOR
if mount | grep -q $flashdevice; then
	diskmounted=1
else
	diskmounted=0
fi

syslog() {
	severity=$1
	shift
	logger -p daemon.$severity -t flashmounter -- $*
}

syslog notice Starting flashmounter!
while true; do
	if [ $diskmounted -eq 0 ]; then
		if fdisk -l /dev/${flashdevice} | grep -q ${flashdevice}1; then
			syslog notice 'Mounting card!'
			mount $mountpoint
			rm -f $mountpoint/unmount
			diskmounted=1
		fi
	else
		if mount | grep -q $flashdevice; then
			if [ -e $mountpoint/backup ]; then
				syslog notice 'Backup requested.'
				rm $mountpoint/backup
				backupdate=$(date +%Y%m%e-%H%M%S)
				tar -czf $backuppoint/$backupdate.tgz -C $mountpoint .
				syslog notice "Backup written to $backuppoint/$backupdate.tgz, size $(ls -sh $backuppoint/$backupdate.tgz | cut -f 1 -d \ )"
			elif [ -e $mountpoint/unmount ]; then
				syslog notice 'Unmounting card.'
				rm $mountpoint/unmount
				umount $mountpoint
				diskmounted=0
				while fdisk -l /dev/${flashdevice}1 | grep -q ${flashdevice}1; do
					sleep 2
				done
				syslog notice 'Card has been removed'
			fi
		else
			syslog notice 'Card was manually unmounted'
			diskmounted=0
			while fdisk -l /dev/${flashdevice}1 | grep -q ${flashdevice}1; do
				sleep 2
			done
			syslog notice 'Card has been removed'
		fi
	fi
	sleep 5
done &
