#!/usr/bin/env bash
# write-localnet-addresses

#set -x
#set -e

pipe="/dev/shm/localnet-addresses"

list_localnet_addresses() {
  awk -F \\t '
{
	sprintf ("ip2domain %s", $1) | getline resolved || resolved="n/a";

	"date +\"%d-%m-%Y %H:%M:%S\"" | getline date

	#vendor = substr ($2, 0, 8)
	#gsub (/:/, "", vendor)
	#sprintf ("sed -n -E \"/^%s	/{s///;p}\" /usr/share/arp-scan/ieee-oui.txt", vendor) | getline vendor || vendor="n/a";
	vendor=($3)? $3: "n/a";

	printf ("%s\t%s\t%s\t%s\t%s\n", date, $1, $2, resolved, vendor);
}
'
}

if ! test -e "${pipe}"; then
  mkfifo "${pipe}"
fi

while test -e "${pipe}"; do
  lsip 2>/dev/null \
    | ifne xargs nmap -oX - -sn | xpath -q -n -e '//address/@addr' \
    | sed 's/ addr="\(.*\)"/\1/' | grep -E '^[0-9.]+$' \
    | sort -u \
    | list_localnet_addresses >"${pipe}"
done
