#!/bin/sh
#
# resolvconf  --  Nameserver information manager
#
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# History
# Jun 2003 - Apr 2004: Written by Thomas Hood <jdthood@yahoo.co.uk>

set -e

MYNAME="${0##*/}"
# Once the improved readlink program has made it into coreutils,
# /lib/init/ can be removed from the PATH.
PATH=/lib/init:/bin:/sbin
RUN_DIR=/etc/resolvconf/run
IFACE_DIR="${RUN_DIR}/interface"
RESOLVCONF_FILE="${RUN_DIR}/resolv.conf"
ENABLE_UPDATES_FLAGFILE="${RUN_DIR}/enable-updates"

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

update()
{
	[ -e "$ENABLE_UPDATES_FLAGFILE" ] || return 0
	cd "$IFACE_DIR"
	# "update" scripts must assume that interface files are in the PWD
	run-parts ${1:+--arg="$1"} ${2:+--arg="$2"} /etc/resolvconf/update.d
}

enable_updates()
{
	: >| "$ENABLE_UPDATES_FLAGFILE"
}

disable_updates()
{
	rm -f "$ENABLE_UPDATES_FLAGFILE"
}

case "$1" in
start)
	# The "start" method should _only_ be used at boot time.
	# If you want to update the resolv.conf file then use "reload".
	# On package upgrade, don't run this.
	echo -n "Setting up resolvconf..."
	umask 022
	if [ ! -d "$RUN_DIR" ] ; then
		if [ -L "$RUN_DIR" ] ; then
			# Target of symlink is not a dir
			# Create directory at the target
			if RUN_CANONICALDIR="$(readlink -f "$RUN_DIR")" && [ "$RUN_CANONICALDIR" ] ; then
				if ! mkdir "$RUN_CANONICALDIR" ; then
					echo "failed."
					report_err "Failure creating directory $RUN_CANONICALDIR"
					exit 1
				fi
			else
				echo "failed."
				report_err "The canonical path of the run directory could not be determined"
				exit 1
			fi
		else
			echo "failed."
			report_err "$RUN_DIR is neither a directory nor a symbolic link"
			exit 1
		fi
	fi
	# The run directory exists

	if [ -d "${RUN_DIR}/interface" ] ; then
		rm -f ${RUN_DIR}/interface/*
	else
		if ! mkdir "${RUN_DIR}/interface" ; then
			echo "failed."
			report_err "Failure creating directory ${RUN_DIR}/interface"
			exit 1
		fi
	fi
	# The interface directory exists

	if ! enable_updates ; then
		echo "failed."
		exit 1
	fi
	if ! update -i ; then
		echo "failed."
		exit 1
	fi
	echo "done."
	exit 0
	;;
stop)
	# The "stop" method should only be used at shutdown time.
	echo -n "Stopping resolvconf..."
	if ! disable_updates ; then
		echo "failed."
		exit 1
	fi
	echo "done."
	exit 0
	;;
reload|force-reload)
	# Do it silently
	if [ ! -d "${RUN_DIR}/interface" ] ; then
		report_err "${RUN_DIR}/interface is not a directory"
		exit 1
	fi
	update
	;;
restart)
	echo -n "Restarting resolvconf..."
	if [ ! -d "${RUN_DIR}/interface" ] ; then
		report_err "${RUN_DIR}/interface is not a directory"
		exit 1
	fi
	if ! update ; then
		echo "failed."
		exit 1
	fi
	echo "done."
	exit 0
	;;
enable-updates)
	enable_updates
	;;
disable-updates)
	disable_updates
	;;
*)
	echo "Usage: /etc/init.d/resolvconf {start|stop|reload|restart|force-reload|enable-updates|disable-updates}" >&2
	exit 3
	;;
esac

