#! /usr/bin/perl
# Check ifconfig media settings in FreeBSD
# anders@fupp.net, 2010-02-05

use Getopt::Std;

#bge0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
#	options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
#	ether 00:14:c2:61:2f:23
#	inet 192.168.120.25 netmask 0xffffff00 broadcast 192.168.120.255
#	media: Ethernet autoselect (1000baseTX <full-duplex>)
#	status: active

#/sbin/ifconfig
getopts('i:s:fa');

sub usage {
	print "check_ifconfig_media -i <if> -s <100/1000> [-a (autoneg)] [-f (full duplex)]\n";
	exit(0);
}

usage unless ($opt_i && $opt_s);

$iftxt=`/sbin/ifconfig $opt_i 2>/dev/null`;
open(IFCMD, "/sbin/ifconfig $opt_i 2>/dev/null |");
while (<IFCMD>) {
	if (/^\s+?media: Ethernet (\w+?)\s+?\((\w+) <([\w\-]+)>\)/) {
		$atxt = $1;
		$stxt = $2;
		$dtxt = $3;
		$stxt =~ s@baseTX@@;
	}
}
close(IFCMD);
$stxtck = $opt_s . "baseTX";
#print "atxt=$atxt stxt=$stxt dtxt=$dtxt X\n";

if ($opt_s ne $stxt) {
	print "Speed $stxt, expected $opt_s\n";
	exit(1);
}
if ($opt_a && $atxt ne "autoselect") {
	print "Expected but did not find autoneg\n";
	exit(1);
}
if ($opt_f && $dtxt ne "full-duplex") {
	print "Expected but did not find full-duplex";
	exit(1);
}
print "Media settings for $opt_i OK: $stxt $atxt $dtxt\n";
exit(0);
