#!/bin/sh
# check-link.sh
# tests interface for link
#
# Usage: check-link.sh INTERFACE
#
# Greg Wiley
# greg@orthogony.com
#
# Script is meant for use with the ifupdown
# program as a pre-up command.  It returns
# success if the given interface has a link.
# Created to avoid the laptop boot delay
# caused by trying to DHCP an unconnected
# interface.
#
# Currently uses MII to check link status.
# This might not be universal since not all
# NICs use MII.  It should work for a large
# number of ethernet NICs, though
#
# History:
#  11/15/2001  gjwiley      create
#  11/16/2001  gjwiley      add syntax checking, support
#                             prog checking, comments, etc.
#                             for publish
# TODO:
#  - if useful, add support for non-ether,
#    non-mii xfcs


iface="$1"

# what to grep to determine no link
MIINACK='no link'

# where is ifconfig?
IFCTOOL='/sbin/ifconfig'
IFCCMD="eval ( ${IFCTOOL} ${iface} > /dev/null 2>&1 )"

# the mii link checking program
MIITOOL='/sbin/mii-tool'
MIICMD="${MIITOOL} ${iface}"

# some systems don't use egrep
GREPTOOL='/bin/egrep'
GREPMIICMD="eval ${GREPTOOL} -q '${MIINACK}'" 


#default to internal error return
rval='3';
if [ -f ${MIITOOL} -a -f ${GREPTOOL} -a -f ${IFCTOOL} ]; then
  if [ -x ${MIITOOL} -a -x ${GREPTOOL} -a -x ${IFCTOOL} ]; then
    if [ "x${iface}" != "x" ]; then
      if  ${IFCCMD}; then
        if ( ${MIICMD} | ${GREPMIICMD} ); then
          rval='1'
        else
          rval='0'
        fi
      else
        echo "${0}: invalid interface" >&2
        rval='2'
      fi
    else
      echo "${0}: interface not specified" >&2
      rval='2'
    fi
  else
   echo "${0}: required program not executable." >&2
  fi
else
  echo "${0}: required program not found." >&2
fi

exit ${rval}

