#!/bin/sh
#
# resolvconf  --  Nameserver information manager
#
# chkconfig:	345 09 91
#
# description:	Nameserver information manager
#
# $Id$

MYNAME="${0##*/}"
PATH=/sbin:/bin
RUN_DIR=/etc/resolvconf/run
IFACE_DIR="${RUN_DIR}/interface"
RESOLVCONF_FILE="${RUN_DIR}/resolv.conf"
ENABLE_UPDATES_FLAGFILE="${RUN_DIR}/enable-updates"

. /etc/rc.d/init.d/functions

# need resolv.conf created with sane permission
umask 022

update() {
	[ -e "$ENABLE_UPDATES_FLAGFILE" ] || return 0
	cd "$IFACE_DIR"
	# "update" scripts must assume that interface files are in the PWD
	run-parts /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.
	show "Setting up resolvconf"
	if [ ! -d "$RUN_DIR" ] ; then
		if [ ! -L "$RUN_DIR" ]; then
			fail
			show "$RUN_DIR is neither a directory nor a symbolic link"
			exit 1
		fi
		# Target of symlink is not a dir
		RUN_CANONICALDIR=$(readlink -f "$RUN_DIR")i
		if [ -z "$RUN_CANONICALDIR" ]; then
			fail
			show "canonical path of the run directory could not be determined"
			exit 1
		fi
		# Create directory at the target
		if ! mkdir "$RUN_CANONICALDIR"; then
			fail
		 	show "error creating directory $RUN_CANONICALDIR"
			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
			fail
			show "error creating directory ${RUN_DIR}/interface"
			exit 1
		fi
	fi
	# The interface directory exists

	if ! enable_updates; then
		fail
		show "could not enable updates"
		exit 1
	fi
	update --arg=-i
	RETVAL=$?
	if [ $RETVAL = 0 ]; then
		ok
	else
		fail
	fi
	;;
  stop)
	# The "stop" method should only be used at shutdown time.
	show "Stopping resolvconf"
	disable_updates
	RETVAL=$?
	if [ $RETVAL = 0 ]; then
		ok
	else
		fail
	fi
	;;
  restart|try-restart)
	show "Restarting resolvconf"
	if [ ! -d "${RUN_DIR}/interface" ]; then
		fail
	 	show "${RUN_DIR}/interface is not a directory"
		exit 1
	fi
	if ! enable_updates; then
		fail
		show "could not enabling updates"
		exit 1
	fi
	update
	RETVAL=$?
	if [ $RETVAL = 0 ]; then
		ok
	else
		fail
	fi
	;;
  reload|force-reload)
	# Do it silently
	if [ ! -d "${RUN_DIR}/interface" ]; then
		show "${RUN_DIR}/interface is not a directory"
	 	exit 1
	fi
	update
	exit $?
	;;
  enable-updates)
	enable_updates
	exit $?
	;;
  disable-updates)
	disable_updates
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|reload|force-reload|enable-updates|disable-updates}"
	exit 3
	;;
esac
