#!/bin/ash
# mount helper for fatdog-drive-icon-action-handler.sh
# Copyright (C) James Budiono 2012
# License: GNU GPL Version 3 or later
#
# Need this file so that we can escalate to root cleanly
#
# Parameter: $1-devname (with /dev), $2-mountpoint
# implicitly assumes $USER, assumes $USER won't change after privilege escalation

### configuration
# defaults, overriden by config file below. Settings to be applied for non-root users
ACCESS_MODE=750			# r-x for non-root. Change to 770 for rwx
UMASK_MODE=027			# r-x for non-root. Change to 007 for rwx
ALLOW_OTHER=allow_other	# allow non-root to access ntfs partition
ACCESS_GROUP=$USER		# who are allowed to accesss (default is user's primary group)
DEFAULT_GID=0			# default gid if it can't be found (0 --> root only access)

EVENTMANAGER_CONFIG=/etc/eventmanager
. $EVENTMANAGER_CONFIG	# ACCESS_MODE, UMASK_MODE, ACCESS_GROUP

### run-time variables
ACCESS_GID=				# filled in by get_ACCESS_GID below

##################### helper #######################
# get group id from $ACCESS_GROUP
get_ACCESS_GID() {
	[ -z "$ACCESS_GROUP" ] && ACCESS_GROUP=$USER
	
	ACCESS_GID=$(awk -F: "/^$ACCESS_GROUP/ {print \$3}" /etc/group)
	[ -z "$ACCESS_GID" ] && ACCESS_GID=$(awk -F: "/^$ACCESS_GROUP/ {print \$4}" /etc/passwd)
	[ -z "$ACCESS_GID" ] && ACCESS_GID=$DEFAULT_GID
}

# returns  mount_options
get_vfat_mount_options() {
	# set codepage - for the two that we support anyway
	read codepage < /etc/codepage
	case $codepage in 
		850) mount_options="$mount_options,codepage=850" ;;
		852) mount_options="$mount_options,codepage=850,iocharset=iso8859-2" ;;
	esac
}
 
##################### main #######################
# Parameter: $1-devname (with /dev), $2-mountpoint
[ $# -lt 2 ] && exit
[ $(id -u) -ne 0 ] && exec gtksu "Mounting ${1##*/}" $0 "$@"

mkdir -p "$2"
get_ACCESS_GID
mount_options="gid=$ACCESS_GID,umask=$UMASK_MODE"
if case $(guess_fstype $1) in 
	ntfs) # try all methods, from the most useful to least
		  { #get_ntfs_3g_mount_options
		  [ $(id -un) = $USER ] && ALLOW_OTHER= # clear allow other if requester is root
		  ntfs-3g -o rw,no_def_opts,silent,nonempty,permissions,$ALLOW_OTHER $1 "$2" || 
		  ntfs-3g -o rw,no_def_opts,silent,nonempty,$mount_options,$ALLOW_OTHER $1 "$2" || 
		  ntfs-3g -o ro,no_def_opts,silent,nonempty,$mount_options,$ALLOW_OTHER $1 "$2" || 
		  mount -o ro,$mount_options $1 "$2"
		  } && fatdog-drive-icon-refresh-icon.sh $1
		  ;;
	vfat) # set code page
		  get_vfat_mount_options
		  mount -t vfat -o shortname=mixed,utf8,quiet,$mount_options $1 "$2"
		  ;;
	iso9660)
		  mount -o utf8 $1 "$2"
		  ;;
 	f2fs) # special treatment for f2fs, otherwise conflict with xfs
 		  mount -t f2fs $1 "$2"
 		  ;;
	*)	  # others - just mount it directly
		  mount $1 "$2" ;;
esac; then
	EXIT_CODE=$?
	if [ $EXIT_CODE -eq 0 ]; then
		if [ $(id -un) != $USER ]; then # change permissions if requester is not root
			chgrp $ACCESS_GROUP "$2"
			chmod $ACCESS_MODE "$2"	
		fi
	fi
	exit $EXIT_CODE
fi
