#!/bin/sh

# 01dns-up-totd sets up /etc/resolv.conf for the provider being connected to.
# In conjunction with pppd's usepeerdns option it also handles dynamic dns.
# It expects to be passed the provider name in PPP_IPPARAM.

# If pppconfig has been removed we are not supposed to do anything.

test -f /usr/sbin/pppconfig || exit 0

# If /etc/resolv.conf is not replaced by totd, we don't do anything.
grep "created by totd" /etc/resolv.conf.ppp.bak || exit 0

PROVIDER="$PPP_IPPARAM"
ETC="/etc"
RUNDIR="/var/run/totd"

PPPRESOLV="$ETC/ppp/resolv"
PPPRUNDIR="/var/run/pppconfig"
RESOLVBAK="$PPPRUNDIR/resolv.conf.bak.$PROVIDER"
RESOLVCONF="resolv.conf"

TOTD_CONF="$ETC/totd.conf"
TOTD_PPPCONF="$RUNDIR/totd.conf"
TOTD_PPPCONFTMP="$RUNDIR/totd.conf.tmp$$"

cd "$RUNDIR" || exit 1

# Revert to original resolv.conf bacause we do not have to change it.
test -f "$RESOLVBAK" && cp $RESOLVBAK $RESOLVCONF

test -f $TOTD_PPPCONFTMP && rm $TOTD_PPPCONFTMP
cat $TOTD_CONF | grep -v forwarder > $TOTD_CONFTMP

if [ "$USEPEERDNS" ] && [ "$DNS1" ]; then
    echo "forwarder $DNS1" >> $TOTD_CONFTMP
    if [ "$DNS2" ]; then
	echo "forwarder $DNS2" >> $TOTD_CONFTMP
    fi
fi

grep forward $TOTD_CONFTMP || rm $TOTD_CONFTMP

if [ -f $TOTD_PPPCONF ]; then
    /bin/rm $TOTD_PPPCONF
fi

if [ -f $TOTD_PPPCONFTMP ]; then
    /bin/mv $TOTD_PPPCONFTMP $TOTD_PPPCONF
fi

if [ -f $TOTD_PPPCONF ]; then
    /etc/init.d/totd stop
    /usr/sbin/totd -c $TOTD_PPPCONF &
fi
