#!/usr/bin/perl
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2 dated June,
# 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# If you modify this plugin please be kind and send a copy to mailto@cot.ath.cx
# Thanks
#
# This plugin counts the number of connected users on your teamspeak2 server.
# You have to configure the variables below.

use strict;
use Socket;

##################
# Config Section #
##################

# The Host where your teamspeak server is running on.
my $host = 'localhost';
# The tcp query port.
my $port = 51234;
# The udp ports of the servers you wish to monitor.
# Enter comma separated values. e.g. (8767, 8766, 8876)
my @uports = (8767);

#########################
# End of Config Section #
#########################

my $string = "server_currentusers";

if ( exists $ARGV[0] and $ARGV[0] eq "config" )
{
	print "graph_title Teamspeak User\n";
	print "graph_vlabel Connected Teamspeak Users\n";
	print "graph_category voip\n";
	#print "graph_args --base 1000 -l 0\n";
	print "graph_info This graph shows the number of connected users on a teamspeak2 server\n";
	foreach my $server (@uports)
	{
		print "$server.label Users on $server\n";
		print "$server.type GAUGE\n";
		#print "$server.draw AREA\n";
	}
	exit 0;
}
elsif ( exists $ARGV[0] and $ARGV[0] eq "autoconf" )
{
	my $TSTCON = &tcpConnect($port, $host);
	while(<$TSTCON>)
	{
		if ( $_ =~ /[TS]/ )
		{
			print "Yes\n";
			exit 0;
		}
	}
}
else 
{
	foreach my $server (@uports)
	{
		my $FS = &tcpConnect($port, $host);
		print $FS "si ".$server, "\n\n";
		my $MASK = $string."=*";

		while(<$FS>) 
		{
        		my $input_line = $_;
			if ( $input_line =~ m/($MASK)/ )
			{
				$input_line =~ /(\d+)/;
				print "$server.value $1\n";
				close $FS;
			}
		}
	}
}
sub tcpConnect()
{
	my $proto = getprotobyname('tcp');
	my $port = shift;
	my $host = shift;

	socket(my $FS, PF_INET, SOCK_STREAM, $proto);
	my $sin = sockaddr_in($port, inet_aton($host));

	connect($FS, $sin) or die exit;
	my $old_fh = select($FS); $| = 1; select($old_fh);

	return($FS);
}
