#!/bin/sh

# $Id: init.d,v 1.20 2002/02/24 03:20:55 cph Exp $
#
# Copyright (c) 2000-2002 Massachusetts Institute of Technology
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

# Disable the network interface before suspend; re-enable after.
# Unfortunately requires unloading and reloading the driver.

IFD="/usr/lib/laptop-net/ifd"
IFD_PID="/var/run/ifd.pid"
LINK_CHANGE="/usr/share/laptop-net/link-change"

[ -x "${IFD}" ] || exit 0
[ -x "${LINK_CHANGE}" ] || exit 0

. /usr/share/laptop-net/shared.sh

[ -x "${LINKUP}" ] || exit 0

if [ "${MII_SUPPORTED}" = "yes" ]; then
    IFD_WATCHED="${INTERFACE}"
else
    IFD_WATCHED=""
fi

usage ()
{
    echo "Usage: $0 {start|stop|restart|force-reload|suspend|resume|scheme|profile}"
    exit 1
}

case "${1}" in
    "start")
	[ $# -eq 1 ] || usage
	echo "up" > "${TARGET_FILE}"
	start-stop-daemon --start --pidfile "${IFD_PID}" \
	    --exec "${IFD}" -- "${LINK_CHANGE}" "${IFD_WATCHED}"
	load_module
	;;
    "stop")
	[ $# -eq 1 ] || usage
	echo "down" > "${TARGET_FILE}"
	start-stop-daemon --stop --pidfile "${IFD_PID}" --exec "${IFD}"
	bringdown stop
	unload_module
	;;
    "restart"|"force-reload")
	[ $# -eq 1 ] || usage
	$0 stop
	$0 start
	;;
    "suspend")
	[ $# -eq 1 ] || usage
	cp -p "${STATE_FILE}" "${RESUME_FILE}"
	if kernel_supports_power_management; then
	    :
	else
	    bringdown suspend
	    unload_module
	fi
	;;
    "resume")
	[ $# -eq 1 ] || usage
	if [ -f "${RESUME_FILE}" ]; then
	    RESUME_STATE="$(cat "${RESUME_FILE}")"
	    rm -f "${RESUME_FILE}"
	    if kernel_supports_power_management; then
		choose_scheme
		maybe_restart_dhcp
	    elif [ -n "${MODULE_NAME}" ] \
		 && [ -z "$(cat /proc/modules | grep "^${MODULE_NAME} ")" ]
	    then
		load_module
	    fi
	fi
	;;
    "scheme")
	if [ $# -eq 2 ]; then
	    OLD_SCHEME="$(cat "${SCHEME_FILE}")"
	    NEW_SCHEME="${2}"
	    if [ "${OLD_SCHEME}" != "${NEW_SCHEME}" ]; then
		echo "Changing scheme from ${OLD_SCHEME} to ${NEW_SCHEME}"
		bringdown newscheme
		write_scheme "${NEW_SCHEME}" "user"
		if "${LINKUP}" "${INTERFACE}"; then
		    bringup newscheme
		fi
	    else
		write_scheme "${NEW_SCHEME}" "user"
	    fi
	else
	    [ $# -eq 1 ] || usage
	    cat "${SCHEME_FILE}"
	fi
	;;
    "profile")
	[ $# -eq 1 ] || usage
	cat "${PROFILE_FILE}"
	;;
    *)
	usage
	;;
esac

exit 0
