#!/bin/bash
# os10 ip information
# original by nicksay on macosxhints.com
# fetches a web page every time it runs, so turn down the refresh, okay?

# add the line
#   test -x /usr/local/bin/networkchange && /usr/local/bin/networkchange
# to /System/Library/SystemConfiguration/Kicker.bundle/Contents/Resources/enable-network
# (at the end, but before the 'exit')
# and something like
#   #!/bin/sh
#   /usr/local/bin/ipinfo > /usr/local/var/ipinfo.txt
# to /usr/local/bin/networkchange
# then set geektool to 'cat /usr/local/var/ipinfo.txt'

# displays the internal and external ip addresses for each interface:
#   hostname
#   en0  xxx.xxx.xx.xxx  xxx.xxx.xx.xxx host.domain.tld.
#   en1     xx.x.xx.xxx  xxx.xxx.xx.xxx host2.domain2.tld.

function pad {
    string="$1" ; num="$2"
    count=$(echo -n "$string" | wc -c) ; ((count += 0))
    while (( count < num )) ; do 
        string=" $string"
        ((count += 1))
    done
    echo -n "$string"
}

idx=0 ; mode="media" ; info=$(ifconfig | fgrep -B 3 netmask)
for i in $info ; do
    case "$mode" in
        media)
	    if [[ $i == en* ]] ; then
		media[$idx]=${i%:*} # strip everything after the interface name
		mode="ip"
	    fi
            ;;
        ip)
            if [[ "$i" == [0-9]*.[0-9]*.[0-9]*.[0-9]* ]] ; then
                # internal ip
                ip[$idx]=$i

                # external ip
                extip[$idx]=$(curl -s -m 4 --interface ${media[$idx]} http://antiflux.org/ip/text)
                # hostname
                if [[ -n ${extip[$idx]} ]] ; then
                    extname[$idx]=$(dig -x ${extip[$idx]} +short)
                fi

                ((idx += 1)) ; mode="media"
            fi
            ;;
    esac
done

# print hostname
hostname

# print ip info
for ((i=0 ; i < ${#media[*]} ; i++)) ; do
    if [[ $ip ]] ; then
        ip=$(pad ${ip[$i]:-unknown} 15)
        extip=$(pad ${extip[$i]:-unknown} 15)
        echo "${media[$i]} $ip $extip ${extname[$i]}"
    fi
done