#!/bin/sh

###########################################################################
### ipfrommac.sh
### This script is an meant for users to run with root permissions in Linux.
### It will find an LXI instrument's IP Address from a user input MAC Address
### by searching a subnet with the nmap command. LXI instrument MAC Addresses
### are printed on the bottom decal. 
### Rev 1.01
### June, 2009
### ZTEC Instruments Inc.
### Shawn Smith
############################################################################

## Usage:
##   ./ipfrommac.sh <macaddress> <netrange>
## If macaddress or netrange are not supplied, they are prompted for.

MACADDR=
IPADDR=
NETRANGE=192.168.0.1-254

# verify root permissions
ROOT=`id -g`
if [ ${ROOT} != "0" ] ; then
    echo "You must have root permissions to run this script."
    exit 1
fi

# accept MAC as first argument o/w get the MAC from the user
if [ $1 ] ; then 
    MACADDR=$1
else
    echo "Enter MAC address to search network for: "
    ##get input, assign to MACADDR
    ##TODO: filter this and accept upper case and lower case hex, :, and numbers
    read MACADDR
fi

if [ $2 ] ; then 
    NETRANGE=$2
else
    echo "Use default netrange, ${NETRANGE}? y/n"
    read RESPONSE
    case "${RESPONSE}" in
        y|Y|yes|Yes|YES)
        ;;
        *)
            echo "Enter the network range to search (e.g. 192.168.0.1-254):"
            read NETRANGE
        ;;
    esac
fi

echo "Searching ${NETRANGE} ..."

# run the nmap command and scan for the MAC
IPADDR=`/usr/bin/nmap -sP ${NETRANGE} | grep -B 1 -i "${MACADDR}" | awk '{print $2; exit}'`

# display IP
if [ -z ${IPADDR} ] ; then
    echo "Cannot find an IP with MAC Address ${MACADDR} on ${NETRANGE}"
else
    echo "${MACADDR} Located at IP Address: ${IPADDR}" 
fi

