#! /bin/sh
# preinst script for root-daemon
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>

case "$1" in
    install|upgrade)
	# 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 ! grep -q ^rootd: /etc/group; then 
	    addgroup --system rootd 
	fi
	if ! grep -q ^rootd: /etc/passwd; then
	    #echo Adding system user: rootd.
	    adduser --system --ingroup rootd \
		--gecos "Anonymous rootd" \
		--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
	usermod -d "/var/spool/rootd"   rootd
	usermod -g "rootd"              rootd
	usermod -s "/bin/false"         rootd

	# 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 777 /var/spool/rootd/tmp
	fi

	if [ ! -d /var/spool/rootd/pub ] ; then 
	    mkdir -p /var/spool/rootd/pub
	    chmod 777 /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
	;;

    abort-upgrade)
	;;
    *)
        echo "preinst called with unknown argument \`$1'" >&2
        exit 0
    ;;
esac

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

#DEBHELPER#

exit 0


