#!/bin/sh -e
# Post-install script for the Debian wu-ftpd package.
#
# Re-written in shell by Chris Butler <chrisb@debian.org>
# 
# Original perl from Peter Tobias, later changed by Heiko Schlittermann
# and Josip Rodin. Re-written for DebConf by Chris Butler.

. /usr/share/debconf/confmodule

WU_FTPD="/usr/sbin/wu-ftpd"
DEFAULT_OPTS="-l"
ADDFTPUSER="/usr/sbin/addftpuser"
RMFTPUSER="/usr/sbin/rmftpuser"
INETD_CONF="/etc/inetd.conf"

if [ "$1" = "configure" ]; then

	if [ -f "/etc/cron.monthly/wu-ftpd-academ" ]; then
		mv /etc/cron.monthly/wu-ftpd-academ /etc/cron.monthly/wu-ftpd-academ.obsolete
	fi

	# Get rid of old alternatives
	if [ -h "/etc/alternatives/ftpd" ]; then
		update-alternatives --remove ftpd /usr/sbin/wu-ftpd
	fi

	# Sort out /etc/ftpusers stuff
	if [ -h "/etc/ftpusers" ]; then
		TMPFILE="`tempfile`"

		cp /etc/ftpusers $TMPFILE
		rm /etc/ftpusers
		mv $TMPFILE /etc/ftpusers
	fi

	if [ -h "/etc/wu-ftpd/ftpusers" ]; then
		rm /etc/wu-ftpd/ftpusers
	fi

	# Check for old binaries in ~ftp/bin (are /bin/ls and ~ftp/bin/ls the same?)
	db_get wu-ftpd/update-binaries
	
	if [ "$RET" = "true" ]; then
		$ADDFTPUSER --update-binaries
	fi

	db_get wu-ftpd/anonymous
	if [ "$RET" = "true" ]; then
		$ADDFTPUSER --configure
	else 
		$RMFTPUSER --configure
	fi

	db_get wu-ftpd/run_mode
	RUNMODE="$RET"

	# stop debconf interactions, to avoid update-inetd's bad interactions with debconf when xinetd is installed (debian bug #489494)
	db_stop
	
	if [ -z "$2" ]; then
		update-inetd --group STANDARD --add "#<off># ftp\t\tstream\ttcp\tnowait$max_opt\troot\t/usr/sbin/tcpd\t$WU_FTPD $DEFAULT_OPTS" </dev/null >/dev/null
	fi
	
	if [ "$RUNMODE" = "inetd" ]; then
		if [ -x /etc/init.d/wu-ftpd ] && [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
			invoke-rc.d wu-ftpd stop >&2
		else
			/etc/init.d/wu-ftpd stop >&2
		fi
		update-inetd --enable ftp >/dev/null
	else
		if ! [ -e "/etc/default/wu-ftpd" ]; then
			cat >/etc/default/wu-ftpd <<EOF
# Defauts for /etc/init.d/wu-ftpd
#
# This file is used when wu-ftpd is running in standalone daemon mode, edit
# /etc/inetd.conf if you are running wu-ftpd from inetd.

# Options to pass to wu-ftpd - see wu-ftpd(8) for details
WU_OPTIONS="$DEFAULT_OPTS"

# Whether to run the daemon on startup
RUN_DAEMON=yes
EOF
		fi
		update-inetd --disable ftp >/dev/null
	fi
	# Check for existence of ~ftp/dev/null
	HOMEFTP=`getent passwd ftp | cut -f6 -d:`

	if [ -n "$HOMEFTP" ] && [ -d "$HOMEFTP" ] && ! [ -e "$HOMEFTP/dev/null" ]; then
		echo >&2
		echo "Creating required file $HOMEFTP/dev/null..." >&2

		chmod 0111 "$HOMEFTP/dev" || mkdir --mode=0111 "$HOMEFTP/dev" 
		mknod "$HOMEFTP/dev/null" c 1 3
		chmod 0666 "$HOMEFTP/dev/null"
	fi
fi # ($1 == "configure")

#DEBHELPER#
