#!/bin/sh

# Automount script, called for sd[a-z]1 devices by custom command in mdev.conf

mount_base="/media"
mountinfo_media="${mount_base}/automount_info/media"
mountinfo_device="${mount_base}/automount_info/device"
mountinfo_file="${mountinfo_device}/$MDEV"

# test ext3 before ext2 to avoid mounting ext3 devices in ext2 backwards compatibility mode
FILESYSTEMS="vfat ext3 ext2 ntfs"

MOUNT_OPTS="-r -noatime"

# Log stdout and stderr
exec 1>/tmp/automount.log
exec 2>&1
set -x

# Work out next available auto mount location
getmountpoint()
{
	if [ ! -e "${1}/disk" ]
	then
		echo "disk"
		return
	fi

	n=1
	while [ $n -lt 256 ]
	do
		if [ ! -e "${1}/disk-${n}" ]
		then
			echo "disk-${n}"
			return
		fi
		let n=n+1
	done
}

if [ "$ACTION" = "add" ]
then
	mountpoint=$(getmountpoint $mountinfo_media)

	mkdir -p $mountinfo_device $mountinfo_media "${mount_base}/${mountpoint}"

	for fs in ${FILESYSTEMS}
	do
		if mount -t $fs ${MOUNT_OPTS} $MDEV "${mount_base}/${mountpoint}"
		then
			echo $mountpoint > "$mountinfo_file"
			echo $MDEV > "${mountinfo_media}/${mountpoint}"
			echo "==> Mounted $MDEV ($fs) on ${mount_base}/${mountpoint}" >/dev/console
			exit 0
		fi
	done

	# Mount attempts failed... remove mountpoint directory
	rm -rf "${mount_base}/${mountpoint}"

else
	mountpoint="$(cat $mountinfo_file)"

	if [ -n "$mountpoint" ]
	then
		umount -f "${mount_base}/${mountpoint}"
		rm -rf "${mount_base}/${mountpoint}" $mountinfo_file "${mountinfo_media}/${mountpoint}"
		echo "==> Unmounted $MDEV (${mount_base}/${mountpoint})" >/dev/console
		exit 0
	fi
fi
