#! /bin/sh

set -e

case "$1" in
    configure)
	# Install user rootd for anonymous file access in /var/spool/rootd 
	# directory. 
	# The lines below are taken from the mysql-server package, and
	# modified to reflects the needs of rootd. 

	# Make sure we can add a user properly 
	if [ ! -x "`which adduser`" ]; then 
	    echo "I need adduser(8) from the adduser package !";
	    exit 1;
	fi
	if [ ! -x "`which addgroup`" ]; then 
	    echo "I need addgroup(8) from the adduser package !";
	    exit 1;
	fi
	if [ ! -x "`which usermod`" ]; then
	    echo "I need usermod(8) from the passwd package !";
	    exit 1;
	fi
	
	# Now we have to ensure the following state:
	#   /etc/passwd: rootd:x:Anonymous rootd:/var/spool/rootd:/bin/false
	#   /etc/group:  rootd:x:72:rootd
	if ! getent group rootd > /dev/null; then 
	    addgroup --system rootd 
	fi
	if ! getent passwd rootd > /dev/null; then
	    #echo Adding system user: rootd.
	    adduser 				\
		--system 			\
		--disabled-login			\
		--ingroup rootd 		\
		--gecos "Anonymous rootd" 	\
		--shell /bin/false		\
		--home /var/spool/rootd 	\
		rootd >/dev/null
	fi

	# creating rootd home directory
	if ! test -d /var/spool/rootd; then
	    mkdir /var/spool/rootd
	fi

	# modifying the user
	# usermod -c "Anonymous rootd"    rootd > /dev/null
	# usermod -d "/var/spool/rootd"   rootd > /dev/null
	# usermod -g "rootd"              rootd > /dev/null
	# usermod -s "/bin/false"         rootd > /dev/null

	# Since the home directory was created before putting the user
	# into the rootd group and moreover we cannot guarantee that
	# the permissions were correctly *before* calling this script,
	# we fix them now. 
	#echo 
	#echo "SECURITY: Fixing permission of /var/spool/rootd !"
	#echo "(I.e. replacing GIDs other than root and rootd with rootd.)"
	#echo
	chown rootd:rootd /var/spool/rootd
	find /var/spool/rootd \
	    -not \( -group root -or -group rootd \) \
	    -exec chgrp rootd {} \;

	# Create the tmp and pub directories in /var/spool/rootd and
	# make them world read- and writeable. 
	if [ ! -d /var/spool/rootd/tmp ] ; then 
	    mkdir -p /var/spool/rootd/tmp
	    chmod 1777 /var/spool/rootd/tmp
	fi

	if [ ! -d /var/spool/rootd/pub ] ; then 
	    mkdir -p /var/spool/rootd/pub
	    chmod 1777 /var/spool/rootd/pub
	fi

	# Nothing to be done here
	# if [ "$1" = "upgrade" ]
	# then
	#     start-stop-daemon --stop --quiet --oknodo  \
	#         --pidfile /var/run/root.pid  \
	#         --exec @prefix@/sbin/root 2>/dev/null || true
	# fi
	;;
    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 0
	;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#