#!/bin/sh
#
# cfs_mkkey for CFS 1.3.4 or later - mab 11/1997
# Usage: cfs_mkkey OLD_DIR NEW_DIR
#
# The cfs_mkkey command creates a "private" copy of the key material
# linked to an encrypted CFS directory.  It creates a new directory,
# containing a copy of the key and a link to the real encrypted
# directory.  The passphrase for the new directory can be changed
# without changing the original directory's passphrase, allowing
# different users of the same shared data to have their own
# passphrases.  Once a key has been copied with cfs_mkkey, cfs_attach to the
# new directory will work on the encrypted data in the old directory.
#
# Note that cfs_mkkey operates on encrypted directories, not the attached
# names in /crypt.
#
# This will someday be replaced by a compiled c program, which will
# eliminate the link ambiguity noted below.


CMD=`basename $0`
if [ -z "$1" -o -z "$2" ]; then
	echo "Usage: $CMD old_dir new_dir"
	exit 1
fi

if [ ! -x $1/. ]; then 
	echo "$CMD: $1 not readable or not a directory"
	exit 1
fi

OLD=`cd $1/.; /bin/pwd` || exit 1
NEW=$2

## We want to only dereference the last link, so this is wrong:
if [ -h "$OLD/..data" ]; then
	OLDDIR=`cd $OLD/..data; /bin/pwd` || exit 1
else
	OLDDIR=$OLD
fi
## Instead, we'd rather have something like:
#if [ -h "$OLD/..data" ]; then
#    OLDDIR=$OLD/..data
#    while [ -h $OLDDIR ]; do
#	OLDDIR=`readlink $OLDDIR`
#    done
#else
#    OLDDIR=$OLD
#fi
## but we don't have a shell version of readlink...
## in environments where this is a problem (e.g., home directories that
## live in funny places, with symlinks providing a standard /home),
## one can always just fix the link by hand.

if [ ! -r "$OLD/..k" ]; then
	echo "$CMD: $OLD is not a readable CFS directory"
	exit 1
fi
if [ ! -r "$OLDDIR/..." ]; then
	echo "$CMD: $OLDDIR is not a readable CFS directory"
	exit 1
fi

if [ -e "$NEW" ]; then
	echo "$CMD: $NEW already exists"
	exit 1
fi

mkdir $NEW || exit 1
cp $OLD/..k $NEW || exit 1
ln -s $OLDDIR $NEW/..data || exit 1
exit 0


