#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Description: interface alias

## function: dhcp_alias_up, dhcp_alias_down
dhcp_alias_up() {

  ALIASDEV="$1"
  DEVICE=`echo "$ALIASDEV" | cut -d: -f1`

  OLDIP=`/sbin/ifconfig $DEVICE | grep "inet addr" | cut -d: -f2 | cut -d' ' -f1`
  OLDNM=`/sbin/ifconfig $DEVICE | grep "inet addr" | cut -d: -f4 | cut -d' ' -f1`
  dhclient $DEVICE
  IP=`/sbin/ifconfig $DEVICE | grep "inet addr" | cut -d: -f2 | cut -d' ' -f1`
  NETMASK=`/sbin/ifconfig $DEVICE | grep "inet addr" | cut -d: -f4 | cut -d' ' -f1`
  GATEWAY=`/sbin/route -n | grep -e "$DEVICE$" | grep -e "^0.0.0.0" | awk '{ print $2; }'`

  if [ "$GATEWAY" != "" ]; then /sbin/route del default gw $GATEWAY dev $DEVICE; fi
  /sbin/ifconfig $DEVICE $OLDIP netmask $OLDNM
  /sbin/ifconfig $ALIASDEV $IP netmask $NETMASK
  if [ "$GATEWAY" != "" ]; then /sbin/route add default gw $GATEWAY dev $DEVICE; fi
}

dhcp_alias_down() {

  ALIASDEV=$1
  /sbin/ifconfig $ALIASDEV down

}

## main
if [ "$1" != "start" -a "$1" != "stop" -a "$1" != "restart" ]; then
  echo "Usage: $0 [start|stop|restart]"
  exit 0
fi

if [ "$1" = "restart" ]; then
  $0 stop
  $0 start
  exit 0
fi

while read key value; do
  if [ "$key" = "" ]; then continue
  elif [ "$key" = "iface" ]; then
    device=`echo "$value" | awk '{ print $1; }'`
    proto=`echo "$value" | awk '{ print $3; }'`

    # check if the device exists
    found=0
    alias=`echo $device | cut -d: -f2`
    for dev in `cat /proc/net/dev | awk -F: '/eth.:|tr.:/{print $1}'`; do
      if [ "$dev:$alias" = "$device" ]; then found=1; break; fi
    done
    if [ $found -eq 0 ]; then continue; fi

    if [ "$proto" = "dhcp" ]; then 
      case "$1" in
        "start") dhcp_alias_up $device ;;
        "stop") dhcp_alias_down $device ;;
      esac
    else
      case "$1" in
        "start") /sbin/ifup -i /etc/network/interfaces.alias $device ;;
        "stop") /sbin/ifdown -i /etc/network/interfaces.alias $device ;;
      esac
    fi
  elif [ "$key" = "mapping" ]; then
    device=$value
    case "$1" in
      "start") /sbin/ifup -i /etc/network/interfaces.alias $device ;;
      "stop") /sbin/ifdown -i /etc/network/interfaces.alias $device ;;
    esac
  fi
done < /etc/network/interfaces.alias
  
