#!/bin/sh

# $Id: init.d,v 1.33 2003/11/02 04:45:00 cph Exp $
#
# Copyright 2000,2001,2002,2003 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.

set -e

IFD="/usr/lib/laptop-net/ifd"
[ -x "${IFD}" ] || exit 0

LINK_CHANGE="/usr/share/laptop-net/link-change"
[ -x "${LINK_CHANGE}" ] || exit 0

SHARED_SH="/usr/share/laptop-net/shared.sh"
[ -f "${SHARED_SH}" ] || exit 0
. "${SHARED_SH}" || exit 0

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

IFD_PID="/var/run/ifd.pid"

INTERFACE="${INTERFACE:-eth0}"
if [ "${MII_SUPPORTED}" = "yes" ]; then
    IFD_MANAGED="${INTERFACE}"
else
    IFD_MANAGED=
fi

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

start_ifd ()
{
    load_module "${INTERFACE}"
    start-stop-daemon --start --pidfile "${IFD_PID}" \
	--exec "${IFD}" -- "${LINK_CHANGE}" ${IFD_MANAGED}
    [ "${MII_SUPPORTED}" = "yes" ] || bringup "${INTERFACE}" start
}

stop_ifd ()
{
    bringdown "${INTERFACE}" stop
    start-stop-daemon --stop --oknodo --pidfile "${IFD_PID}" --exec "${IFD}"
    unload_module "${INTERFACE}"
}

case "${1}" in
    ("start")
	[ $# -eq 1 ] || usage
	clean_state
	start_ifd
	;;
    ("stop")
	[ $# -eq 1 ] || usage
	stop_ifd
	;;
    ("restart"|"force-reload")
	[ $# -eq 1 ] || usage
	stop_ifd || true
	start_ifd
	;;
    ("suspend")
	[ $# -eq 1 ] || usage
	touch "${RESUME_FILE}"
	stop_ifd || true
	;;
    ("resume")
	[ $# -eq 1 ] || usage
	if [ -f "${RESUME_FILE}" ]; then
	    rm -f "${RESUME_FILE}"
	    start_ifd || true
	fi
	;;
    ("scheme")
	if [ $# -eq 2 ]; then
	    OLD_SCHEME="$(read_scheme_file "${INTERFACE}")"
	    NEW_SCHEME="${2}"
	    if [ "${OLD_SCHEME}" != "${NEW_SCHEME}" ]; then
		echo "Changing scheme from ${OLD_SCHEME} to ${NEW_SCHEME}"
		bringdown "${INTERFACE}" newscheme
		write_scheme "${INTERFACE}" "${NEW_SCHEME}" "user"
		if "${LINKUP}" "${INTERFACE}"; then
		    bringup "${INTERFACE}" newscheme
		fi
	    else
		write_scheme "${INTERFACE}" "${NEW_SCHEME}" "user"
	    fi
	else
	    [ $# -eq 1 ] || usage
	    read_scheme_file "${INTERFACE}"
	fi
	;;
    ("profile")
	[ $# -eq 1 ] || usage
	cat "${PROFILE_FILE}"
	;;
    (*)
	usage
	;;
esac
