#!/bin/sh

CFSFS=/.cfsfs
CRYPT=/crypt

echo -n "Configure cfs now [Y/n]? "
read input
if expr "$input" : '[Nn]' > /dev/null
then
	exit 0;
fi

echo -n "Use default Cryptographic Filesystem Configuration [Y/n]? "
read input
if expr "$input" : '[Nn]' > /dev/null
then
	if ! grep -q '^CFSFS=$' /etc/init.d/cfsd 
	then
		CRYPT=`grep '^CRYPT=' /etc/init.d/cfsd | sed -e "s/^CRYPT=\(.*\)$/\1/"`
		CFSFS=`grep '^CFSFS=' /etc/init.d/cfsd | sed -e "s/^CFSFS=\(.*\)$/\1/"`
	fi
	echo -n "Enter server mount point [$CFSFS] "
	read input
	if [ ! -z $input ]
	then
		CFSFS=$input
	fi
	echo -n "Enter client mount point [$CRYPT] "
	read input
	if [ ! -z $input ]
	then
		CRYPT=$input
	fi
fi

OLDCRYPT=""
OLDCFSFS=""
if ! grep -q '^CFSFS=$' /etc/init.d/cfsd 
then
	OLDCRYPT=`grep '^CRYPT=' /etc/init.d/cfsd | sed -e "s/^CRYPT=\(.*\)$/\1/"`
	OLDCFSFS=`grep '^CFSFS=' /etc/init.d/cfsd | sed -e "s/^CFSFS=\(.*\)$/\1/"`
fi

/etc/init.d/cfsd stop

mv /etc/init.d/cfsd /etc/init.d/cfsd_tmp$$
sed -e "s!^CFSFS=.*\$!CFSFS=$CFSFS!;s!^CRYPT=.*\$!CRYPT=$CRYPT!" /etc/init.d/cfsd_tmp$$ > /etc/init.d/cfsd
rm /etc/init.d/cfsd_tmp$$
chmod 755 /etc/init.d/cfsd

if [ "$OLDCRYPT" != "$CRYPT" -o "$OLDCFSFS" != "$CFSFS" ]
then
	echo
	echo "Old directories $OLDCRYPT and $OLDCFSFS not automatically removed."
	echo "Please remove by hand."
	echo
fi

if [ ! -e $CFSFS ] 
then
	echo "Creating directory $CFSFS"
	mkdir -p -m 0 $CFSFS 
fi
if [ ! -e $CRYPT ]
then
	echo "Creating directory $CRYPT"
	mkdir -p -m 755 $CRYPT
fi

if grep -q "Cryptographic Filesystem export" /etc/exports
then
	mv /etc/exports /etc/exports_tmp$$
	sed -e "/^# Automatically added for use by cfs\$/ d;/^.*localhost(rw).*#.*Cryptographic Filesystem export.*\$/ d;" /etc/exports_tmp$$ > /etc/exports
	chmod 644 /etc/exports
	rm /etc/exports_tmp$$
fi

echo "# Automatically added for use by cfs" >> /etc/exports
echo "$CFSFS localhost(rw)  # Cryptographic Filesystem export" >> /etc/exports

if [ -x /etc/init.d/nfs-server ]; then
	echo "Restarting nfs-server"
	/etc/init.d/nfs-server restart > /dev/null
fi
if [ -x /etc/init.d/nfs-kernel-server ]; then
	echo "Restarting nfs-kernel-server"
	/etc/init.d/nfs-kernel-server restart > /dev/null
fi

/etc/init.d/cfsd start
