#!/bin/sh
# $Id: ifdl,v 1.3 2004/01/14 07:24:27 dleonard Exp $
# Wrapper around ifup for handling multiple network configurations at the user
# level.

##############################################################
# help
##############################################################
help () {
 echo
 echo "Usage: ifdl [-b] [-f] [-h] [-l] [-v] <interface> [network location]"
 echo " <interface> can be any single network interface or -a for all"
 echo " [-b|--backup] back up conf files to prevent accidental destruction"
 echo " [-f|--force] force overwrite conf files"
 echo " [-h|--help] this help list"
 echo " [-l|--list] lists all defined network locations"
 echo " [-v|--verbose] passes --verbose flag to ifup"
 echo " [network location] denotes the suffix you have appended to the"
 echo "   relevant configuration files.  See /etc/network/ifdl.conf for a"
 echo "   listing of those files."

 exit 0
} #help

##############################################################
# list_nets
##############################################################
list_nets () {
 prime_file=`echo $FILES | awk '{print $1}'`
 locs=`ls $prime_file.* | sed "s#$prime_file\.##g"`

 if [ "$locs" ]; then
  echo "Network locations found:"
  for i in $locs ; do
   echo $i
  done

 else
  error "No custom network locations found"
 fi

 exit 0
} #list

##############################################################
# error
##############################################################
error () {
 echo "An error occurred"
 echo "$*"

 exit 1
} #error

#########################################################
# VARS
backup=
conf="/etc/network/ifdl.conf"
force=
ifup_args=
interface=
network=

if [ -f $conf ]; then
 . /etc/network/ifdl.conf
else
 error "Conf file [$conf] not found"
fi

args="$*"

for arg in $args ; do
 arg_dash=`echo $arg | grep - 2>/dev/null`
 if [ "$arg_dash" ]; then
  if [ "$arg_dash" = "-a" ]; then
   interface="-a"

  elif [ "$arg" = "--backup" -o "$arg" = "-b" ]; then
   backup=1

  elif [ "$arg" = "--force" -o "$arg" = "-f" ]; then
   force=1

  elif [ "$arg" = "--list" -o "$arg" = "-l" ]; then
   list_nets

  elif [ "$arg" = "--verbose" -o "$arg" = "-v" ]; then
   ifup_args="$ifup_args --verbose"

  elif [ "$arg" = "--help" -o "$arg" = "-h" ]; then
   help

  else
   help
  fi

 else
  if [ ! "$interface" ]; then
   interface="$arg"

  elif [ ! "$network" ]; then
   network="$arg"

  else
   error "Unknown argument [$arg]"
  fi
 fi
done

for i in $FILES; do
 if [ -f $i.$network ]; then
  if [ "$backup" ]; then
   cp $force $i $i.bak
  fi

  cp $force $i.$network $i
 fi
done

if [ ! "$interface" ]; then
 error "No interface specified"
fi

$IFUP $ifup_args $interface
