#!/bin/bash
#==============================================================================
# autoehd
#   Copyright (C) W. Michael Putello <mike@flyn.org>, 2002
#   Copyright © Jan Engelhardt <jengelh [at] gmx de>, 2005 - 2006
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License as
#   published by the Free Software Foundation; either version 2 of
#   the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
#   General Public License for more details.
#
#   You should have received a copy of the GNU General Public
#   License along with this program; if not, write to:
#   Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
#   Boston, MA  02110-1301  USA
#
#   -- For details, see the file named "LICENSE.GPL2"
#==============================================================================

CONF=/etc/security/pam_mount.conf

USAGE="[USER] [OPTION]...

  -h, -?   print this message"

while :; do
	case "$1" in
		-h | "-?" )
			echo -e usage: ${0##*/} "$USAGE" >&2
			exit 1 ;;
		-?* )
			echo "${0##*/}: unrecognized option: $1" >&2;
			exit 1 ;;
		* )
			break ;;
	esac
	shift
done

if [ -n "$1" ]; then
	USER="$1";
fi

if [ ! -f "$CONF" ]; then
	echo "${0##*/}: $CONF is missing"
	exit 1
fi

REGEX="^volume[[:space:]]\+\($USER\|*\|@$GROUP\)[[:space:]]\+";
LINE=`grep -m1 "$REGEX" "$CONF"`;
if [ -z "$LINE" ]; then
    echo "${0##*/}: could not find configuration for $USER in $CONF" >&2;
    exit 1;
fi

MNTPT=`echo "$LINE" | awk '{ print $6 }'`;
OPTIONS=`echo "$LINE" | awk '{ print $7 }'`;
CIPHER=`echo "$LINE" | awk '{ print $8 }'`;
KEYPATH=`echo "$LINE" | awk '{ print $9 }'`;
VOLUME=`echo "$LINE" | awk '{ print $5 }'`;


if [ "$MNTPT" == "-" ]; then
	MNTPT="";
fi

if [ "$OPTIONS" == "-" ]; then
	OPTIONS="";
else
	OPTIONS="-o $OPTIONS"
fi

if [ "$CIPHER" == "-" ]; then
	mount $OPTIONS $VOLUME $MNTPT
else
	openssl enc -d -$CIPHER -in $KEYPATH | mount -p0 $OPTIONS $VOLUME $MNTPT
fi
