#!/bin/bash
# Need bash because we use nullglob, GLOBIGNORE
#
# Script to update the pdnsd configuration
#
# N.B.: Resolvconf may run us even if pdnsd is not running.
#
# Assumption: On entry, PWD contains the resolv.conf-type files
#
# Requires server section in /etc/pdnsd.conf with label="resolvconf"
#
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# History
# May 2004: Written by Thomas Hood <jdthood@yahoo.co.uk>

set -e
PATH=/bin:/sbin

[ -x /usr/sbin/pdnsd-ctl ] || exit 0
[ -e /var/cache/pdnsd/pdnsd.status ] || exit 0

# 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
}

### Compile ordered list of resolv.conf-type files ###
PATTERNS="eth* ath* wlan* ppp* *"
if [ -r /etc/resolvconf/interface-order ] ; then
	PATTERNS="$(sed -e 's/#.*//' -e '/^$/d' -e '/^lo/d' /etc/resolvconf/interface-order || :)"
fi
shopt -s nullglob
GLOBIGNORE="lo*"
uniquify $PATTERNS
RSLVCNFFILES="$RSLT"
 
NMSRVRS=""
if [ "$RSLVCNFFILES" ] ; then
	uniquify $(sed -n 's/^[[:space:]]*nameserver[[:space:]]\+//p' $RSLVCNFFILES)
	NMSRVRS="${RSLT// /,}"
fi

if [ "$NMSRVRS" ] ; then
	OUTPUT="$(/usr/sbin/pdnsd-ctl server resolvconf up "$NMSRVRS" || true)"
else
	OUTPUT="$(/usr/sbin/pdnsd-ctl server resolvconf down || true)"
fi

# Convert newlines to spaces
set -f   # Disable pathname expansion
OUTPUT="$(echo $OUTPUT)"

OUTPUT="${OUTPUT/Opening socket \/var\/cache\/pdnsd\/pdnsd.status Succeeded}"
[ -z "$OUTPUT" ] || echo "$OUTPUT"
exit 0
