#!/usr/local/bin/perl -w

=head1 NAME

Munin Plugin for Teamspeak3 Servers

Displays the number of connected users on TS3 servers

=head1 INSTALLATION

- Copy this plugin in your munin plugins directory

=over 2

    ln -s /usr/share/munin/plugins/teamspeak_user /etc/munin/plugins/teamspeak_user

=back

After the installation you need to restart your munin-node service.

=head1 CONFIGURATION

You need to create a file named teamspeak_user placed in the directory
/etc/munin/plugin-conf.d/ with the following config:

=over 2

    [teamspeak_user]
    env.hostname 127.0.0.1
    env.port 10011
    env.username serveradmin
    env.password <password>

=back

=head1 AUTHORS

Tim Wulkau - www.wulkau.de

=head1 CHANGELOG

23.01.22 - v0.5
           -add environment variables
18.11.10 - v0.4
           -added queryuser login
           -subtract queryclients from usercount (tanks to Jakob Lenfers for the idea)
02.10.10 - v0.3
           -fixed welcomemessage error
31.01.10 - v0.2
           -fixed multiserver support
           -corrected usercount
17.01.10 - v0.1
           -initial release

=cut

use strict;
use Net::Telnet;

# CONFIG HERE!
my $hostname  = $ENV{hostname}  || "localhost"; # serveraddress
my $port      = $ENV{port}      || 10011;       # querryport (default: 10011)
my @serverids = $ENV{serverids} || (1);         # array of virtualserverids (1,2,3,4,...)
my $username  = $ENV{username}  || "";          # only set if the default queryuser hasn't enough rights (should work without this)
my $password  = $ENV{password}  || "";

# SCRIPT START!
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_info This graph shows the number of connected users on a Teamspeak3 server\n";
  foreach my $server (@serverids)
  {
    print "$server.label Users on Serverid $server\n";
    print "$server.type GAUGE\n";
    #print "$server.draw AREA\n";
  }
  exit 0;
}
else
{
  my $telnet = new Net::Telnet(Timeout=>5, Errmode=>"return", Prompt=>"/\r/");
    if (!$telnet->open(Host=>$hostname, Port=>$port)) {
    die exit;
  }
  $telnet->waitfor("/Welcome to the TeamSpeak 3 ServerQuery interface/");
  foreach my $server (@serverids)
  {
    $telnet->cmd("use sid=$server");
    $telnet->waitfor("/error id=0 msg=ok/");
    if($username && $password) {
      $telnet->cmd("login $username $password");
      $telnet->waitfor("/error id=0 msg=ok/");
    }
    $telnet->cmd("serverinfo");

    my $clients = 0;
    my $queryclients = 0;
    my $line = $telnet->getline(Timeout=>5);
    if ($line =~ m/virtualserver_clientsonline=(\d+) /) {
      $clients = $1;
    }
    if ($line =~ m/virtualserver_queryclientsonline=(\d+) /) {
      $queryclients = $1;
    }
    $telnet->waitfor("/error id=0 msg=ok/");
    print "$server.value ".($clients - $queryclients)."\n";
  }
  $telnet->close;
}
exit;
