#!/bin/bash

# this variable is only set if the usepeerdns pppd option is being used
[ "$USEPEERDNS" ] || exit 0

# multilink, serial, wirelessmodem interfaces pass cli configured
# interface name as the 1st word in ipparam while pppoe and pppoa
# interfaces pass just the configured interface name using ipparam
device=`echo "$6"|awk '{ print $1 }'`

# only do this script for ml, wan, pppoe, pppoa, wlm interfaces
# any new interfaces using ppp in CLI will have to be passed
# using ipparam and have to add themselves here
case "$device"X in
 ml* | wan* | pppoa* | pppoe* | wlm* );;
 * ) 
    logger -p debug -t "vyatta-usepeerdns" \
    Invalid interface $device to update resolv.conf on link up
    exit 0;;
esac

# create the file if it does not exist
if [ ! -e /etc/resolv.conf ]; then
  : > /etc/resolv.conf
fi

# store nameservers received for this ppp device in its own resolv-$device.conf file
# TODO : need to lock /etc/ppp/resolv.conf while copying it
cp -p /etc/ppp/resolv.conf /etc/ppp/resolv-$device.conf

# check if received nameservers for this device exist in /etc/resolv.conf. If not append them
nameserver_array=($( grep '^nameserver' /etc/ppp/resolv-$device.conf | awk '{print $2}' ))
ns_array_len=${#nameserver_array[*]}
i=0
while [ $i -lt $ns_array_len ]; do
 if ! grep -q "${nameserver_array[$i]}[[:space:]].*$device$" /etc/resolv.conf; then
   echo "nameserver ${nameserver_array[$i]} # nameserver added by $device" >> /etc/resolv.conf
 fi
 let i++
done

# restart dnsmasq and ntp here, just as done in /opt/vyatta/sbin/vyatta-system-nameservers

# restart dnsmasq if dns-forwarding is configured
if cli-shell-api existsActive service dns forwarding; then
   /opt/vyatta/sbin/vyatta-dns-forwarding.pl --update-dnsforwarding --outside-cli >&/dev/null
fi

# restart ntp if ntp is configured
if [ -f /etc/ntp.conf ] && grep -q "^server" /etc/ntp.conf; then
   /usr/sbin/invoke-rc.d ntp restart >&/dev/null
fi

exit 0
