#!/usr/bin/php
<?php
error_reporting( E_ALL & ~E_NOTICE ); //to avoid of the crap generation

/* // do not remove this line

/////////////////////////////////////////////////////////////////////////////////////////////////////

Murmur users online grapher PHP using ICE, shows averages
ver 0.2 2011.06.10, 15:44 
author _KaszpiR_ kaszpir at gmail dot com
code is under GPL

Requirements:
- PHP installed in CLI (so you can run it in command line)
  Make sure the first line of this file points to the pworking php cli inrepreter
- ICE framework on server
- Murmur server with ICE enabled

/////////////////////////////////////////////////////////////////////////////////////////////////////

Configuration:
1. link creation
create a symlink to thie file in the following format:
    murmurice_ip_port_sid_description_avg
where ip/port correspond to the ip and port on which the mumble ice interface listens to
sid is the server id we want to query (mumble can run multiple servers )
description - any kind of short text where _ will be replaced with spaces

By default script tries to connect 127.0.0.1:6502 and query server id 1

2. ice profile configuration
 This is not needed with ice 3.4.1
 Scroll down in this file and change 
 $ice_profile = 'Murmur'; 
 to the profile that is installed on the server, this is required if you have multiple Ice profiles for various applicaitions.


/////////////////////////////////////////////////////////////////////////////////////////////////////

Script returns:
mute number = number of users currently muted
deaf number = number of users currently deafened on server
suppress number = number of users supressed on server, that is server forced muting
selfmute number = number of users currently muted by themselves
selfdeaf number = number of users currently deafened by themselves
avgperchan number = number of average users per channel

error number = this is set to 1 when there is error with communicatind with server via ice

On any error script exits with status 1, otherwise it is 0.

///////////////////////////////////////////////////////////////////////////////////////////////////
Changelog:

- ver 0.2 2011.06.10, 15:44 stable
  fix for ICE 3.4.1 that does not use Ice_loadprofile() function
  extended description
  fixed typos
  fixed warning messages in logs
  release

- ver 0.1 2011.04.2, 12:32 stable
  ICE 3.4.1 fix

- ver 0.2 2010.02.16 beta
  first private release


///////////////////////////////////////////////////////////////////////////////////////////////////
Todo:
- load iceprofile from env var


///////////////////////////////////////////////////////////////////////////////////////////////////


*/ //do not remove this line

$ice_profile = 'Murmur';


// Define STDIN in case if it is not already defined by PHP for some reason 
if(!defined("STDIN"))
{
    define("STDIN", fopen('php://stdin','r'));
}

if(!defined("STDERR"))
{
    define("STDERR", fopen('php://stderr','w'));
}



list($dummy,$ip,$port,$serverid,$desc) = explode("_",$argv[0],5);

if(!$ip) $ip="127.0.0.1";
if(!$port) $port=6502;
if(!$serverid) $serverid=1;

/////////////////////////////////////////////////////////////////////////////////////////////////////
//autoconf test
if(isset($argv[1]) && $argv[1] == "autoconf")
{
	if(FALSE)
	{
	}
	else 
	{
		fwrite(STDOUT, "No\n");
		fwrite(STDERR, "symlink ".$argv[0]." to somethilg like ".$argv[0]."_127.0.0.1_6502_1_description_here \n");
	}
	return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
//config, set rrd files
if(isset($argv[1]) && $argv[1] == "config")
{
	if(TRUE)
	{
	// yea dirty hack 
		echo "graph_title Mumble Average Users per chan ".($desc?" on ".str_replace("_"," ",$desc):"")."\n";
		echo "graph_vlabel Number\n";
		echo "graph_category VoIP\n";
		echo "graph_info This graph shows the average number of users per channel on a murmur server, and other lower values\n";
		echo "mute.label Muted\n";
		echo "deaf.label Deafen\n";
		echo "suppress.label Suppressed\n";
		echo "selfmute.label Self Muted\n";
		echo "selfdeaf.label Self Deafen\n";
		echo "avgperchan.label Users per chan\n";
		echo "error.label Server status error\n";
		
		$arr=array("mute","deaf","suppress","selfmute","selfdeaf","avgperchan","error");
		foreach($arr as $field){
		    echo "".$field.".draw LINE1\n";
		    echo "".$field.".type GAUGE\n";
		}


		return 0;
		
	}else {
		echo "RTFM\n";
		return 1;
	}
	return 0;
}




$mute=0;
$deaf=0;
$suppress=0;
$selfmute=0;
$selfdeaf=0;

$avg_perchan = array();
$avg = 0;
//echo "Serverid:".$serverid."\n";


if (Ice_intversion() >= 30400) {
    require 'Ice.php';
    require 'Murmur.php';
    } else {
      Ice_loadProfile($ice_profile);
    }

try {
  if (Ice_intversion() >= 30400) {
    $initData = new Ice_InitializationData;
    $initData->properties = Ice_createProperties();
    $initData->properties->setProperty("Ice.MessageSizeMax", "65536");
    $ICE = Ice_initialize($initData);
    }          


  $base = $ICE->stringToProxy("Meta:tcp -h ".$ip." -p ".$port);
  $meta = $base->ice_checkedCast("::Murmur::Meta");

  $servers = $meta->getBootedServers();
  $default = $meta->getDefaultConf();
  foreach($servers as $s) {
    $name = $s->getConf("registername");
    if (! $name) {
      $name =  $default["registername"];
    }

    if($s->id() !=$serverid) continue;

    $chanlist = $s->getChannels();
    $channels = count($chanlist);
    foreach($chanlist as $chan=>$c){
	$links+=count($c->links);
    }
    $players = $s->getUsers();
    foreach($players as $id => $p) {
        if($p->userid ==-1)
	    $online_noreg++;
        else
    	    $online_reg++;
    if($p->mute) $mute++;
    if($p->deaf) $deaf++;
    if($p->suppress) $suppress++;
    if($p->selfMute) $selfmute++;
    if($p->selfDeaf) $selfdeaf++;
    $avg_perchan[$p->channel]++;
    }
    }

    $active_chans = count(array_keys($avg_perchan));
    if($active_chans ==  0 ) $avg = 0;
    else $avg = round( count($players) / $active_chans);

} catch (Ice_LocalException $ex) {
    fwrite(STDERR,"ERROR: IP=".$ip.", Port=".$port.", Id=".$serverid."\n");
    fwrite(STDERR,$ex);
	echo "mute.value 0\n";
	echo "deaf.value 0\n";
	echo "suppress.value 0\n";
	echo "selfmute.value 0\n";
	echo "selfdeaf.value 0\n";
	echo "avgperchan.value 0\n";
	echo "error.value 1\n";

return 1;
}
echo "mute.value ".$mute."\n";
echo "deaf.value ".$deaf."\n";
echo "suppress.value ".$suppress."\n";
echo "selfmute.value ".$selfmute."\n";
echo "selfdeaf.value ".$selfdeaf."\n";
echo "avgperchan.value ".$avg."\n";
echo "error.value 0\n";
return 0;
?>