#!/bin/sh

# Network helpers
#################

getInfIp() {
	ifconfig "$1" 2>/dev/null | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'
}

getWanMac() {
	# LTE devices dont have WAN eth
	[ -z "$WAN_ETH" ] && inf=eth0 || inf="$WAN_ETH"
	cat /sys/class/net/$inf/address
}
getWanInf() {
	[ ! -z "${MOBILE_DEV}" ] && echo wwan0 && return
	[ -z "$WAN_VLAN" ] && echo br-wan || echo "br-vlan${WAN_VLAN}"
}
getWanIp() {
	wanInf=`getWanInf`
	getInfIp "$wanInf"
}
getWanSpeed() {
	# limit LTE speed to 50Mbps
	[ ! -z "${MOBILE_DEV}" ] && echo 50 && return
	cat /sys/class/net/$WAN_ETH/speed 2>/dev/null
	[ $? -ne 0 ] && echo 100
}

getLanMac() {
	cat /sys/class/net/$LAN_ETH/address
}

getVlanInf() {
	local vlan="$1"
	local wan=`echo $WAN_ETH | awk -F '.' '{printf $1}'`
	echo "$wan.$vlan"
}

# Get default gateway IP
getGateway() {
	route | grep default | awk '{printf $2}'
}
pingAddress() {
	ping -c 3 -w 3 $1 2>/dev/null | grep 'received' | awk '{ print $4 }'
}

getIpFromMac() {
	local mac=`echo "$1" | tr [A-Z] [a-z]`

	if [ ! -z "$2" ] ; then
		ip neighbor show dev $2 | grep -v :: | grep "$mac" | awk '{print $1}'
	else
		ip neighbor show | grep -v :: | grep "$mac" | awk '{print $1}'
	fi
}

resolveHostname() {
	nslookup $1 2>/dev/null | grep Address | grep -v '#53' \
		| sed 's/[^0-9. ]//g' | tail -n 1 | awk -F " " '{print $2}'
}

addressIsIp() {
	ip="$1"

	if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
		echo "1"
	else
		echo ""
	fi
}