#!/bin/sh

set -e

[ -x /usr/sbin/totd ] || exit 0
[ -x /lib/resolvconf/list-records ] || exit 1

TOTD_CONF=/etc/totd.conf

# Stores arguments (minus duplicates) in RSLT, separated by spaces
# Doesn't work properly if an argument itself contain whitespace
uniquify()
{
	RSLT=""
	while [ "$1" ] ; do
		for E in $RSLT ; do
			[ "$1" = "$E" ] && { shift ; continue 2 ; }
		done
		RSLT="${RSLT:+$RSLT }$1"
		shift
	done
}

ETCRESOLVCONF="/etc/resolvconf"
TMP_FILE="${ETCRESOLVCONF}/run/totd_new.$$"
clean_up() { rm -f "$TMP_FILE" ; }
trap clean_up EXIT
rm -f "$TMP_FILE"

# Get list of records, excluding all those for the loopback interface
RSLVCNFFILES="$(/lib/resolvconf/list-records | sed -e '/^lo$/d' -e '/^lo[.]/d')"

### Compile semicolon-separated list nameservers ###
NMSRVRS=""
if [ "$RSLVCNFFILES" ] ; then
	uniquify $(sed -n -e 's/^[[:space:]]*nameserver[[:space:]]\+//p' $RSLVCNFFILES)
	NMSRVRS="$RSLT"
fi

echo ";; totd.conf generated by $0" > "$TMP_FILE"

if [ -f $TOTD_CONF ]; then
	cat $TOTD_CONF \
		| sed -e 's/forwarder[[:space:]]\+//g' \
		| sed -e '/^$/d'
		>> $TMP_FILE
fi

for N in $NMSRVRS; do echo "forwarder $N" >> "$TMP_FILE" ; done

if [ "$1" = "-i" ] ; then
        mv -f "$TMP_FILE" "$TOTD_CONF"
        exit 0
fi

if [ -x /usr/bin/diff ] && [ -f "$TOTD_CONF" ] && \
	/usr/bin/diff -q "$TOTD_CONF" "$TMP_FILE" > /dev/null ; then
        # No change
	rm -f "$TMP_FILE"
else
        mv -f "$TMP_FILE" "$TOTD_CONF"
	[ -x /etc/init.d/totd ] && /etc/init.d/totd restart > /dev/null 2>&1 \
		|| :
fi
