#!/bin/sh -e

# Automatically configure the server used by Leafnode and the access
# controls in /etc/hosts.allow.  Mostly written by Joey Hess
# <joeyh@master.debian.org> with some additional bugs by Mark Brown
# <broonie@tardis.ed.ac.uk>

# Originally written for the Debian Leafnode package

CONFIG=/etc/news/leafnode/config
SAMPLE=/usr/share/doc/leafnode/examples/config.example
FETCHNEWS=/usr/sbin/fetchnews

# Guess the name of the upstream server to use
if [ -e /etc/news/server ]; then
	remoteserver=`cat /etc/news/server`
	if [ "$remoteserver" = "`hostname`" -o "$remoteserver" = "`hostname -f`" ]; then
		remoteserver=
	fi
fi

echo -n "
Leafnode configuration
----------------------

To what server will leafnode connect to download news? [$remoteserver] "

read answer
if [ -z "$answer" ]; then
	answer=$remoteserver;
fi

echo -n "Setting up leafnode to use $answer as the nntp server..."

# Keep as many settings we don't know about as possible
if [ -e $CONFIG ]; then
	cp $CONFIG ${CONFIG}.new
	cp $CONFIG ${CONFIG}.0
else
        # Debhelper may decided to compress the sample file, so we
	# handle either case.
        if [ -f ${SAMPLE}.gz ] ; then
	   gunzip -c ${SAMPLE}.gz > ${CONFIG}.new
	else
	   cp $SAMPLE ${CONFIG}.new
	fi
fi

# Eeek!  This is horrible.
sed -e "/server.*=/ c\\
server = $answer\\" \
	< ${CONFIG}.new > ${CONFIG}

if ! grep "server.*=" ${CONFIG} > /dev/null ; then
	echo server = $answer > ${CONFIG}.tmp
	cat ${CONFIG}.tmp ${CONFIG}.new > ${CONFIG}
	rm -f ${CONFIG}.tmp
fi

rm -f ${CONFIG}.new
echo "done."

echo -n "
Do you wish to update the list of availible groups now? [yN] "

answer=""
while [ ! $answer ]; do
	read answer
	case "$answer" in
	[Yy]*)
		answer=y
		;;
	[Nn]*)
		answer=n
		;;
	'')
		answer=n
		;;
	*)
		echo -n "Do you wish to update the list of avalible groups now? [yN]"
		answer=""
		;;
	esac
done

if [ "$answer" = "y" ]; then
	$FETCHNEWS -f
fi
