#!/bin/bash

# solaris ifconfig <-> iputils ifconfig output wrapper
#
# (c) 2007 - Guido S. Nickels <gsn@kernel-oops.de>
#
# this is a simple script for providing iputils ifconfig style output on
# solaris systems
#
# currently only the output of "ifconfig" without any options can be
# simulated. There is no input wrapping at all and no options are supported.

IFCONFIG="/sbin/ifconfig.real"

if [ "$1" != "" ]; then
 if [ "$1" != "lo" -a "$(echo $1|grep '^eth[[:digit:]]')" = "" ]; then
  $IFCONFIG $@
  exit 0
 fi
fi

funct_space()
{
 FAKEDEV_LENGTH=$(echo $1|wc -c)
 FAKEDEV_SPACE=$((10-$FAKEDEV_LENGTH))
 for ((i=0;i<$FAKEDEV_SPACE;i++)); do
  echo -n " "
 done
}

COUNT=0

for DEV_CUR in $($IFCONFIG -a|grep -o '^[^[:space:]]*'); do
 DEV_CUR=${DEV_CUR%:}
 case $DEV_CUR in
  lo*)
   FAKEDEV="lo"
   DEVLINE="${FAKEDEV}$(funct_space $FAKEDEV) Link encap:Local loopback"
   ADDRLINE="          inet addr:127.0.0.1  Mask:255.0.0.0"
   MISCLINE=""
  ;;
  *)
   if [ $COUNT -eq 0 ]; then
    FAKEDEV="eth0"
    ((COUNT++))
   else
    FAKEDEV="$(echo $DEV_CUR|sed -n 's/^[^[:digit:]]*\(.*\)$/eth\1/p')"
   fi

   ADDR="$($IFCONFIG $DEV_CUR|grep -o 'inet \([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}'|awk '{ print $2 }')"
   BCAST="$($IFCONFIG $DEV_CUR|grep -o 'broadcast \([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}'|awk '{ print $2 }')"
   MASK_BIN=$(echo "ibase=16;obase=2;$($IFCONFIG $DEV_CUR|grep -o 'netmask [0-9a-f]\{8\}'|awk '{ print $2 }'|tr '[a-z]' '[A-Z')"|bc)
   DIGIT_COUNT=0
   OCTET=""
   for DIGIT in $(echo $MASK_BIN|grep -o '[[:digit:]]'); do
    if [ $DIGIT_COUNT -lt 8 ]; then
     OCTET[1]="${OCTET[1]}$DIGIT"
    else
     if [ $DIGIT_COUNT -lt 16 ]; then
      OCTET[2]="${OCTET[2]}$DIGIT"
     else
      if [ $DIGIT_COUNT -lt 24 ]; then
       OCTET[3]="${OCTET[3]}$DIGIT"
      else
       OCTET[4]="${OCTET[4]}$DIGIT"
      fi
     fi
    fi
    ((DIGIT_COUNT++))
   done
   for ((i=1;i<5;i++)); do
    DEC_VALUE=$(echo "ibase=2;${OCTET[$i]}"|bc)
    if [ "$MASK" = "" ]; then
     MASK="$DEC_VALUE"
    else
     MASK="${MASK}.$DEC_VALUE"
    fi
   done

   ARP_LINE=$(arp -an|grep "$ADDR"|tr '[a-z]' '[A-Z]')
   ETHER=${ARP_LINE##* }
   
   DEVLINE="${FAKEDEV}$(funct_space $FAKEDEV) Link encap:Ethernet  HWaddr $ETHER"
   ADDRLINE="          inet addr:$ADDR  Bcast:$BCAST  Mask:$MASK"
   MISCLINE="          Interrupt:0 Base address:0x0000
"
  ;;
 esac

 if [ "$1" = "" -o "$1" = "$FAKEDEV" ]; then
 cat << EOC
$DEVLINE
$ADDRLINE
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 MiB)  TX bytes:0 (0.0 MiB)
$MISCLINE
EOC
 fi

done

exit 0
