#!/usr/bin/env bash

. lib.bash || exit

grep_hwdb() {
	systemd-hwdb query "$1" | sed -n "s/^$2=//p"
}

grep_nmap() {
	sed -n "/^${1:0:6} /{s///;p;q}" "$NMAP_MAC_DB"
}

grep_ethers() {
	getent ethers $(echo "$1" | sed 's/../:&/g; s/^://') | awk '{print $2}'
}

NMAP_MAC_DB="/usr/share/nmap/nmap-mac-prefixes"

B=$'\e[1m'
I=$'\e[3m'
U=$'\e[4m'
R=$'\e[m'

arg_mode=

while getopts "m:" OPT; do
	case $OPT in
	m) mode=$OPTARG;;
	esac
done; shift $((OPTIND-1))

if [[ $1 =~ ^MAC=([0-9a-f:]{17}):([0-9a-f:]{17}):([0-9a-f:]{5})$ ]]; then
	echo "destination:"
	$0 -m oui "${BASH_REMATCH[1]}" | sed 's/^/  /'
	echo "source:"
	$0 -m oui "${BASH_REMATCH[2]}" | sed 's/^/  /'
	echo "ethertype: ${BASH_REMATCH[3]}"
	exit
fi

if [[ $1 == *%* ]]; then
	set -- "${1%'%'*}"
fi
if [[ $1 =~ ^fe80::[0-9a-f:]+ff:fe[0-9a-f:]+$ ]]; then
	set -- "$(python -c 'if True:
		import ipaddress
		import sys
		addr = ipaddress.IPv6Address(sys.argv[1])
		iid = bytearray(addr.packed[8:])
		iid[0] ^= 2
		mac = iid[:3] + iid[5:]
		print(mac.hex())
	' "$1")"
fi

mac_re='^[0-9A-Fa-f]{12}$'
mac_re+='|^([0-9A-Fa-f]{6}[-])[0-9A-Fa-f]{6}$'
mac_re+='|^([0-9A-Fa-f]{4}[.]){2}[0-9A-Fa-f]{4}$'
mac_re+='|^([0-9A-Fa-f]{1,2}[:-]){5}[0-9A-Fa-f]{1,2}$'

if [[ ! $mode && $1 =~ $mac_re ]]; then
	mode=oui
fi

show_vendor() {
	local arg=$1
	if have systemd-hwdb; then
		local v=$(grep_hwdb "OUI:$arg" ID_OUI_FROM_DATABASE)
		echo "vendor: ${B}${v:--}${R} (from hwdb)"
	fi
	if [ -s "$NMAP_MAC_DB" ]; then
		local v=$(grep_nmap "$arg")
		echo "vendor: ${B}${v:--}${R} (from nmap)"
	fi
}

case $mode in
	oui)
		arg=$1
		arg=${arg//[:-]}
		arg=${arg^^}
		echo "query: $arg (MAC address)"
		local=$(( 0x${arg:0:2} & 0x2 ))
		multicast=$(( 0x${arg:0:2} & 0x1 ))
		if (( multicast )); then
			echo "kind: multicast"
		elif (( local )); then
			echo "kind: locally administered"
		else
			echo "kind: globally unique"
			show_vendor "$arg"
		fi
		v=$(grep_ethers "$arg")
		if [[ $v ]]; then
			echo "device: ${B}${v:--}${R} (from ethers)"
		fi
		v=$(whatmac -q "$arg")
		if (( $? == 0 )); then
			echo "device: ${U}$v${R} (from whatmac)"
		fi
		;;
	wwn)
		arg=$1
		arg=${arg//[:.-]}
		arg=${arg^^}
		echo "query: $arg (WWN)"
		case $arg in
		1* | 2*) show_vendor "${arg#????}" ;;
		5*) show_vendor "${arg#?}" ;;
		esac
		;;
	*)
		die "mode not specified"
		;;
esac
