#! /bin/sh

#  /etc/init.d/amd: start and stop the 4.4BSD automouter.
#  Copyright (C) 1996-98 by Dominik Kubla, <kubla@Uni-Mainz.DE> and
#                        Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
#
# AMD needs to be started _AFTER_ NFS and NIS are up...
FLAGS="defaults 35"
# tell debstd that we need to manage this ourselves...
# NO_RESTART_ON_UPGRADE

CONFIGDIR=/etc/amd

# If the package is removed, skip it.
test -x /usr/sbin/amd || exit 0

# If the package is not configured, skip it.
test -f $CONFIGDIR/config || exit 0

# Read the configuration data.
. $CONFIGDIR/config

start_amd() {

    if start-stop-daemon --test --stop --exec /usr/sbin/amd >/dev/null 2>&1; then
	echo "amd is already running"
	exit 1
    fi

    # If the hostname is not a FQHN, add the -d command line switch,
    # so that hostnames in the maps are stripped correctly.
    case `hostname` in
	*.*)	dnsdomain=""
		;;
	*)	dnsdomain="-d `dnsdomainname`"
		;;
    esac

    # Rotate logfile on startup, if SYSLOG is not used.
    case "$LOGFILE" in
	*/*)	savelog -g adm -m 644 -u root -c 4 "$LOGFILE" >/dev/null
		cp /dev/null "$LOGFILE" 
		;;
	syslog)	# Do nothing
		;;
    esac

    if [ -n "$NISMAP" ]; then 
	if [ -n "$NISKEY" ]; then
	    AMDARGS=`ypmatch $NISKEY $NISMAP 2>/dev/null`
	else
	    AMDARGS=`ypcat $NISMAP 2>/dev/null`
	fi
    else
	AMDARGS=`cat $CONFIGDIR/amd.master 2>/dev/null`
    fi

    # If we got no master map, abort ...
    if [ -z "$AMDARGS" ]; then
	echo "$0: WARNING: Couldn't find master map..."
	exit 1
    fi

    echo -n "Starting automounter: amd"
    start-stop-daemon --start --quiet --exec /usr/sbin/amd -- -l $LOGFILE $AMDARGS $dnsdomain
    echo "."
}

stop_amd() {
    # get pid of amd binary for later
    pid=`start-stop-daemon --test --stop --exec /usr/sbin/amd 2>&1 | \
	 perl -n -e 'print "$1\n" if /^would send signal \d+ to (\d+)\.$/i;'`
    if [ -z "$pid" ]; then
	echo "amd not running"
	exit 1
    fi
    echo -n "Stopping automounter: amd"
    start-stop-daemon --stop --signal $1 --quiet --exec /usr/sbin/amd
    # wait until amd has finished; this may take a little bit, and amd can't
    # start while an old one is running
    while kill -0 $pid >/dev/null 2>&1; do
	true
    done
    echo "."
}

case "$1" in
  start)
	start_amd
	;;

  stop)
	stop_amd 15
	;;

  u-stop)
	stop_amd 2
	;;

  restart)
	stop_amd 15
	start_amd
	;;

  u-restart)
	stop_amd 2
	start_amd
	;;

  reload)
	# amd tests itself if its map files have changed, so nothing to do here
	;;
  force-reload)
	# the only thing reload can't do is "rereading" /etc/amd/amd.master,
	# which are command line options. So do a full restart here
	stop_amd
	start_amd
	;;

  *)
	echo "Usage: /etc/init.d/amd {start|[u-]stop|[u-]restart|[force-]reload}"
	exit 1
esac

exit 0
