#!/bin/sh

VERBOSE=1
DEBUG=1
ABORT_ON_FAILURE=1
IGNORE_NONEXISTENT=1
export VERBOSE DEBUG 

cd `dirname $0`

PATH="${PATH}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export PATH   # Just in case...

if [ -n "${DHCP_OLDHOSTINFO}" -a -f "${DHCP_OLDHOSTINFO}" ]; then
  READ_OLDHOSTINFO=1
  sed -e 's/^/OLD_/' "${DHCP_OLDHOSTINFO}" > "${DHCP_OLDHOSTINFO}.old"
  . "${DHCP_OLDHOSTINFO}.old"
  export `sed -e 's/=.*$//' "${DHCP_OLDHOSTINFO}.old"`
  rm -f "${DHCP_OLDHOSTINFO}.old"
fi

if [ -n "${DHCP_HOSTINFO}" -a -f "${DHCP_HOSTINFO}" ]; then
  READ_HOSTINFO=1
  . "${DHCP_HOSTINFO}"
  export `sed -e 's/=.*$//' "${DHCP_HOSTINFO}"`
fi

case "$1" in
  up)
    dir="up.d"
    ;;
  down)
    dir="down.d"
    ;;
  change)
    dir="change.d"
    ;;
  *)
    echo "Usage: $0 up|down|change" 1>&2
    exit 2
    ;;
esac

if [ ! -d "$dir" ]; then
  echo "No such directory '$dir'" 1>&2
  exit 2
fi

failed=""
for i in $dir/K* ; do

  if [ ! -f "$i" ]; then
    if [ -n "$IGNORE_NONEXISTENT" -o -z "$ABORT_ON_FAILURE" ]; then
      continue
    else
      echo "$0: Couldn't find script '$i' going down for '$1'" 1>&2
      failed="$failed 'couldn't find script $i'"
    fi
  fi

  "$i" down
  
  e=$?
  if [ $e -ne 0 -a -n "$ABORT_ON_FAILURE" ]; then
    echo "$0: Script '$i' failed with exit code $e going down for '$1'.  Pressing on..." 1>&2
    failed="$failed 'script $i exited with $e'"
  fi

done

if [ -n "$failed" ]; then
  echo "$0: The following problems occured while bringing the interface down in preparation for '$1': $failed"
  echo "$0: Aborting."
  exit 1
fi

if [ "$1" = "down" ]; then
  exit 0
fi

for i in $dir/S*; do

  if [ ! -f "$i" ]; then
    if [ -n "$IGNORE_NONEXISTENT" -o -z "$ABORT_ON_FAILURE" ]; then
      continue
    else
      echo "$0: Couldn't find script '$i' for '$1'; aborting" 1>&2
      exit 1
    fi
  fi

  "$i" "$1"

  e=$?
  if [ $e -ne 0 -a -n "$ABORT_ON_FAILURE" ]; then
    echo "$0: Script '$i' failed with exit code $e for '$1'.  Aborting." 1>&2
    exit $e
  fi


done

exit 0
