#!/bin/bash

#   FILE: passwdehd -- Changes a user's efsk.
# AUTHOR: W. Michael Petullo <mike@flyn.org>
#   DATE: 06 October 2002
# 
# Copyright (C) 2002 W. Michael Petullo <mike@flyn.org>
# 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 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 the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

CONF=/etc/security/pam_mount.conf

USAGE="[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 $USER ";
CIPHER=`grep "$REGEX" "$CONF" | awk '{ print $8 }'`;
KEYPATH=`grep "$REGEX" "$CONF" | awk '{ print $9 }'`;

if [ ! -f "$KEYPATH.old" -a "$UID" -ne 0 ]; then
	echo "${0##*/}: $KEYPATH.old does not yet exist and you can't create it"
	exit 1
fi

if [ -z "$OLD_EFSK_PASSWORD" ]; then
	echo -n "(current) EFSK password: "
	stty -echo >/dev/tty;
	read OLD_EFSK_PASSWORD </dev/tty; echo;
	stty echo >/dev/tty;
fi

if [ -z "$NEW_EFSK_PASSWORD" ]; then
	echo -n "New EFSK password: "
	stty -echo >/dev/tty;
	read NEW_EFSK_PASSWORD </dev/tty; echo;
	echo -n "Retype new EFSK password: "
	read VERIFY </dev/tty; echo;
	if [ "$NEW_EFSK_PASSWORD" != "$VERIFY" ]; then
		echo "Sorry, passwords do not match"
		stty echo >/dev/tty;
		exit 1
	fi
	stty echo >/dev/tty;
fi

export OLD_EFSK_PASSWORD
export NEW_EFSK_PASSWORD

cp "$KEYPATH" "$KEYPATH.old";
openssl enc -d -$CIPHER -pass env:OLD_EFSK_PASSWORD -in "$KEYPATH" | \
    openssl enc -$CIPHER -pass env:NEW_EFSK_PASSWORD >"/tmp/passwdehd.$$";
cp "/tmp/passwdehd.$$" "$KEYPATH";
# Don't use mv because of permission issues.
# WHAT issue? mv _keeps_ permissions, cp does not necessarily without -p
rm "/tmp/passwdehd.$$";
