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

set -e

echo_usage() { echo "Usage: resolvconf (-u|-d IFACE|-a IFACE)" ; }

PATH=/sbin:/bin
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 ; }

[ -L /etc/resolv.conf ] || { report_err "/etc/resolv.conf must be a symlink"; exit 1; }

# Check arguments
CMD="$1"
case "$CMD" in
  -u)
  	if [ "$2" ] ; then
		report_err "The -u option does not take an argument"
		echo_usage >&2
		exit 1
	fi
	;;
  -a|-d)
	IFACE="$2"
	if [ -z "$IFACE" ] ; then
		report_err "No interface name specified"
		echo_usage >&2
		exit 1
	fi
	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 hyphen" ; exit 1 ; }
	[ "${IFACE#\~}" = "$IFACE" ] || { report_iface_err "Initial tilde" ; exit 1 ; }
	;;
  *)
	report_err "Invalid argument"
	echo_usage >&2
	exit 1
	;;
esac

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

cd "$IFACE_DIR"

case "$CMD" in
  -u) : ;;
  -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 99
	;;
esac

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

exec run-parts "--arg=$CMD" ${IFACE:+--arg="$IFACE"} /etc/resolvconf/update.d

