#!/bin/sh
#===============================================================================
#
#  mmc
#
#  Copyright (C) 2009 by Digi International Inc.
#  All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License version 2 as published by
#  the Free Software Foundation.
#
#
#  !Description: mount/umount mmc/sd cards
#
#===============================================================================

SCRIPTNAME="$(basename ${0})"

usage() {
	[ "${SCRIPTNAME}" = "mmc-mount" ] && printf "\nMount mmc storage drives\n"
	[ "${SCRIPTNAME}" = "mmc-umount" ] && printf "\nUmount mmc storage drives\n"
	printf "\nUsage: ${SCRIPTNAME} [OPTIONS]\n\n"
}

while getopts "" c; do
	case "${c}" in
	*)
		usage
		exit
		;;
	esac
done

if [ "${SCRIPTNAME}" = "mmc" ]; then
	# Script run via mdev
	case "${ACTION}" in
	add)
		# Create mountpoint and mount the mmc device
		if mkdir -p /media/${MDEV} && ! mountpoint -q /media/${MDEV}; then
			mount /dev/${MDEV} /media/${MDEV}
		fi
		;;
	remove)
		# Umount and then remove mountpoint
		if grep -q "/dev/${MDEV}[[:blank:]]" /proc/mounts; then
			mdir=$(sed -ne "s,/dev/${MDEV}[[:blank:]]\+\([^[:blank:]]\+\)[[:blank:]].*,\1,g;T;p" /proc/mounts)
			umount "${mdir}"
			rmdir -- "${mdir}" 2>/dev/null
		fi
		;;
	esac
elif [ "${SCRIPTNAME}" = "mmc-mount" ]; then
	# Script run via command line [mmc-mount]
	for i in /sys/block/mmcblk[0-9]/mmcblk[0-9]p[1-9]*; do
		[ "${i}" = "/sys/block/mmcblk[0-9]/mmcblk[0-9]p[1-9]*" ] && continue
		device="$(basename ${i})"
		if mkdir -p /media/${device} && ! mountpoint -q /media/${device}; then
			echo -n "Mounting /dev/${device} on /media/${device}: "
			mount /dev/${device} /media/${device}
			echo "done."
		fi
	done
elif [ "${SCRIPTNAME}" = "mmc-umount" ]; then
	# Script run via command line [mmc-umount]
	for i in /media/mmcblk*; do
		[ "${i}" = "/media/mmcblk*" ] && continue
		if mountpoint -q $i; then
			umount "$i"
			rmdir -- "$i" 2>/dev/null
		fi
	done
fi
