#!/bin/bash
# Need bash because of use of ${FOO/bar}
#
# resolvconf (-d IFACE|-a IFACE)
#
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# History
# Jun 2003 - May 2004: Written by Thomas Hood <jdthood@yahoo.co.uk>

set -e

PATH=/bin:/sbin
MYNAME="${0##*/}"
# Note that /etc/resolvconf/run may be a symlink
RUN_DIR=/etc/resolvconf/run
IFACE_DIR="${RUN_DIR}/interface"
ENABLE_UPDATES_FLAGFILE="${RUN_DIR}/enable-updates"

report_err() { echo "${MYNAME}: Error: $*" >&2 ; }

CMD="$1"
case "$CMD" in
	-a|-d) : ;;
	*) report_err "No command argument supplied" ; exit 1 ;;
esac

IFACE="$2"
[ "$IFACE" ] || { report_err "No interface name specified" ; exit 1 ; }
report_iface_err() { report_err "$* not allowed in interface record name" ; }
[ "${IFACE/\/}" = "$IFACE" ] || { report_iface_err "Slash" ; exit 1 ; }
[ "${IFACE/ }" = "$IFACE" ] || { report_iface_err "Space" ; exit 1 ; }
[ "${IFACE#.}" = "$IFACE" ] || { report_iface_err "Initial dot" ; exit 1 ; }
[ "${IFACE#\~}" = "$IFACE" ] || { report_iface_err "Initial tilde" ; exit 1 ; }

[ -d "$IFACE_DIR" ] || { report_err "$IFACE_DIR is not a directory" ; exit 1 ; }

cd "$IFACE_DIR"

case "$CMD" in
	-a)
		OLD_CONTENT=""
		[ -f "$IFACE" ] && OLD_CONTENT="$(cat "$IFACE")"
		NEW_CONTENT="$(sed 's/#.*//' -)"
		# Proceed only if content has changed. The test here can't
		# eliminate 100% of redundant invocations of update scripts
		# because we don't do any locking; however it certainly does
		# eliminate most of them.
		if [ "$NEW_CONTENT" = "$OLD_CONTENT" ] ; then 
			exit 0
		fi
		IFACE_TMPFILE="${IFACE}_new.$$"
		cleanup() { rm -f "$IFACE_TMPFILE" ; }
		trap cleanup EXIT
		echo "$NEW_CONTENT" > "$IFACE_TMPFILE"
		mv -f "$IFACE_TMPFILE" "$IFACE"
		;;
	-d)
		if [ ! -s "$IFACE" ] ; then
			rm -f "$IFACE"
			exit 0
		fi
		rm -f "$IFACE"
		;;
	*)
		report_err "Command not recognized"
		exit 1
		;;
esac

[ -e "$ENABLE_UPDATES_FLAGFILE" ] || exit 0

# The "update" scripts must look for interface files in the
# current working directory
run-parts "--arg=$CMD" "--arg=$IFACE" /etc/resolvconf/update.d

