#!/bin/sh -e
#
#    ipnow - best effort to find the local host's ip address as of now
#    Copyright (C) 2011 Canonical Ltd.
#
#    Authors: Dustin Kirkland <kirkland@ubuntu.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

usage() {
	echo
	echo "Usage:"
	echo "  ipnow [-4|-6] [interface]"
	echo
	echo "  - The default is -6, if -4 is not specified"
	echo "  - The interface will be determined from the default route, if unspecified."
	echo
	exit 1
}

# Handle command line arguments
IPV=
INTERFACE=
case "$#" in
	0)
		true
	;;
	1)
		case "$1" in
			-4) IPV=4;;
			-6) IPV=6;;
			*)  INTERFACE="$1";;
		esac
	;;
	2)
		case "$1" in
			-4) IPV=4;;
			-6) IPV=6;;
			*)  usage;;
		esac
		INTERFACE="$2"
	;;
	*)
		usage
	;;
esac

# If interface is unspecified, find interface providing default route
if [ -x "$INTERFACE" ]; then
	case "$IPV" in
		4)
			INTERFACE=$(awk 'END {print $1}' /proc/net/route)
		;;
		*)
			INTERFACE=$(awk '$10 != "lo" { iface=$10 ; }; END { print iface; }' /proc/net/ipv6_route)
		;;
	esac
fi

ipv4() {
	ipaddr=$(LC_ALL=C /sbin/ip -4 -o addr list dev "$INTERFACE" scope global)
	ipaddr=${ipaddr#* inet }
	ipaddr=${ipaddr%%/*}
}

ipv6() {
	ipaddr=$(LC_ALL=C /sbin/ip -6 -o addr list dev "$INTERFACE" scope global)
	ipaddr=${ipaddr#* inet6 }
	ipaddr=${ipaddr%%/*}
}

# Find the ip address
case "$IPV" in
	4)
		ipv4
	;;
	6)
		ipv6
	;;
	*)
		ipv6
		[ -z "$ipaddr" ] && ipv4
	;;
esac
echo "$ipaddr"
