#! /bin/sh
# postinst script for shfs

set -e

AMD_CONF_DIR=""
for d in /etc/am-utils/ /etc/ /etc/amd/; do
	if [ -f "$d/amd.conf" ]; then
		AMD_CONF_DIR="$d"; break
	fi
done

AMD_SERVICE=""
for d in /etc/init.d/am-utils /etc/init.d/amd /etc/rc.d/init.d/am-utils /etc/rc.d/init.d/amd; do
	if [ -x "$d" ]; then
		AMD_SERVICE="$d"; break
	fi
done

case "$1" in
    configure)

	umask 0022
        if [ -n "$AMD_CONF_DIR" -a -n "$AMD_SERVICE" ]; then
		cat >$AMD_CONF_DIR/amd.shfs  <<-EOF
			*       type:=program;fs:=\${autodir}/\${rhost}\${rfs};mount:="$AMD_CONF_DIR/mount mount \${uid} \${key} \${fs}";unmount:="$AMD_CONF_DIR/umount umount \${fs}"
		EOF

		cat >>$AMD_CONF_DIR/amd.conf <<-EOF
			# SHFS: AUTO ADDED
			[ /shfs ]
			map_name = $AMD_CONF_DIR/amd.shfs
			# SHFS: END
		EOF

		cat >$AMD_CONF_DIR/mount <<"EOF"
#!/bin/sh
#
# This amd automounter script is called when remote host should be
# (un)mounted under /shfs directory. Feel free to modify this script 
# to satisfy your needs (e.g add special options to shfsmount, 
# restrict mount to some users, etc.).
#
# mount user-id key dir
# umount dir

case `basename $0` in
    "mount")
	ID="$1"; KEY="$2"; DIR="$3"
	if [ -z "$ID" -o -z "$KEY" -o -z "$DIR" ]; then
		echo "Invalid usage."
		exit 2
	fi

	RUSER=`echo "$KEY" | cut -d"%" -f1`
	RHOST=`echo "$KEY" | cut -d"%" -f2-`

	SSH_AGENT_PID=`ps -C ssh-agent -opid=,uid= | sed -n "s/^[ \t]\{1,\}\([0-9]\{1,\}\)\{1,\}[ \t]\{1,\}$ID\$/\1/p" | tail -1`
	SSH_AUTH_SOCK=`find /tmp -follow -maxdepth 4 -type s -user "$ID" | grep ssh | grep agent | tail -1`

	if [ ! -z "$SSH_AGENT_PID" -a ! -z "$SSH_AUTH_SOCK" ]; then
		export SSH_AGENT_PID SSH_AUTH_SOCK
	fi

	mkdir -p $DIR
	shfsmount -u "$ID" -O "-o BatchMode=yes" "$RUSER@$RHOST" "$DIR" -o own,uid="$ID" >/dev/null 2>&1

	if [ $? -ne 0 ]; then
		rmdir $DIR
		exit 2
	else
		exit 0
	fi
	;;
	
     umount)
	DIR="$1"
	if [ -z "$DIR" ]; then
		echo "Invalid usage."
		exit 2
	fi

	if umount "$DIR" >/dev/null 2>&1; then
		rmdir "$DIR" >/dev/null 2>&1
		exit 0
	fi
	exit 2
    ;;

    *)
	echo "Invalid usage."
	exit 2
esac
EOF

		chmod u+x $AMD_CONF_DIR/mount
		ln -f -s mount $AMD_CONF_DIR/umount
		mkdir -m 755 /shfs

		set +e
		$AMD_SERVICE stop
		$AMD_SERVICE start
		set -e
	fi

	set +e
	/sbin/depmod -a
	set -e
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)

    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

#DEBHELPER#

exit 0


