#!/usr/bin/perl
#
#

use warnings;
use strict;
use Net::Telnet;

# Tweak and check
my $password = 'removed';
my $timeout = 15;

sub switch_exec($$) {
	my ($cmd, $conn) = @_;

	# Send the command and get data from switch
	my @data = $conn->cmd($cmd);
	my @lines = ();
	foreach my $line (@data) {
		# Remove escape-7 sequence
		$line =~ s/\x1b\x37//g;
		push (@lines, $line);
	}

	return @data;
}

sub switch_connect($) {
	my ($ip) = @_;

#					Errmode => 'return',
	my $conn = new Net::Telnet(     Timeout => $timeout,
					Dump_Log => 'dumplog',
					Prompt => '/es(\-)?3024|e(\-)?\d+\-\dsw>/i');
	my $ret = $conn->open(  Host => $ip);
	if (!$ret || $ret != 1) {
		return (undef);
	}
	# XXX: Just send the password as text, I did not figure out how to
	# handle authentication with only password through $conn->login().
	#$conn->login(뻔Prompt => '/password[: ]*$/i',
	#	       Name => $password,
	#	       Password => $password);
	$conn->cmd($password);
	# Get rid of banner
	$conn->get;
	return ($conn);
}

sub switch_get_arp($) {
	my ($conn) = @_;

	my @data = switch_exec('ip arp status', $conn);
	foreach (@data) {
# 81.162.241.1    Ethernet       300   00:e0:2b:e0:f3:00 41   swif0 swp24
		$_ =~ /(\d+\.\d+\.\d+\.\d+)\s+\w+\s+\d+\s+(\w\w:\w\w:\w\w:\w\w:\w\w:\w\w)\s+\d+\s+\w+\s+(\w+)/;
		next if (!defined($1));
		next if ($3 eq "NULL");
		print "$1 $2 $3\n";	
	}
	return @data;
}

my $conn = switch_connect($ARGV[0]);
if (!defined($conn)) {
	die "something went wrong!";
}
my @data = switch_exec('sys monitor status', $conn);
my @fields = split(/\s+/, $data[2]);
# The temp fields are 6, 7, 8
print "$fields[7] + $fields[8] + $fields[9]\n";
my $avgtemp = ($fields[7] + $fields[8] + $fields[9]) / 3;
print $avgtemp." avgtemp\n";
$conn->close();

