#!/bin/sh
# Tool for setting which network should be used (without actually bringing up
# any interfaces.)  This is useful for things like wlan where you want to set
# the network before attempting to bring it up due to wireless authentication.

##############################################################
# help
##############################################################
help () {
 echo
 echo "Usage: ifset [-b] [-f] [-h] [-l] [network location]"
 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 " [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"
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" = "--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" = "--help" -o "$arg" = "-h" ]; then
   help

  else
   help
  fi

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

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

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

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

echo "Current configured network [$network]"
