#!/bin/sh
# uam -- pmount helper script
# (c) 2008-2011 Michał Górny
# Released under the terms of the 3-clause BSD license

LIBDIR=/usr/lib/udev/uam

. "${LIBDIR}"/uam-common.sh

try_mountpoint() {
	local _mp mp mpdev ret
	_mp=${1}

	[ -z "${_mp}" ] && return 0
	mp=${MOUNTPOINT_BASE}/${_mp%%/}
	mpdev=$(mp_used "${mp}")

	if [ -z "${mpdev}" ]; then
		debug "... mountpoint ${mp} free, using it."

		MOUNTPOINT=${mp}
		LABEL=${_mp%%/}
		return 1
	else
		debug "... mountpoint ${mp} already used for ${mpdev}."
	fi

	return 0
}

unset DEVNAME DEVPATH LABEL MOUNTPOINT

find_devpath() {
	local x hadargterm
	hadargterm=

	for x; do
		case "${x}" in
			--)
				hadargterm=1
				continue
				;;
			-*)
				# Ignore pmount args
				[ -n "${hadargterm}" ] || continue
				;;
		esac

		if [ -n "${DEVPATH}" ]; then
			LABEL=${x}
			break
		else
			DEVPATH=${x}
		fi
	done
}

find_devpath "${@}"

if [ -z "${DEVPATH}" ]; then
	pmount "${@}"
	exit ${?}
fi

if [ -z "${LABEL}" ]; then
	conf_read TRACE=
	if ! env_populate "${HOOK_PMOUNT_CACHE}"; then
		outmsg "Unable to get device information."
		exit 1
	fi
fi

conf_read TRACE=

debug "Running uam-pmount on ${DEVPATH}."

hook_exec pre-mount

if [ -z "${LABEL}" ]; then
	foreach MOUNTPOINT_TEMPLATES try_mountpoint
fi

if [ -n "${LABEL}" ]; then
	[ -n "${MOUNTPOINT}" ] && set -- "${@}" "${LABEL}"
	pmount "${@}"

	ret=${?}
	if [ ${ret} -eq 0 ]; then
		summary "mounted successfully in ${MOUNTPOINT}."
		hook_exec post-mount
	else
		summary "mount failed."
		hook_exec mount-failed
	fi

	exit 0
else
	debug "... no more mountpoints, failing."
	summary "unable to find a free mountpoint."
	hook_exec mount-failed

	exit 1
fi
