<?php
/*
EDIT THESE SETTINGS TO MATCH YOUR CONFIGURATION
*/
$notify = "name@domain.com";
$rootdir = "/var/www/html/smi";
$dbhost = "localhost";
$dbname = "smi";
$dbuser = "smiuser";
$dbpass = "ch4ng3m3";
$serverhost = "localhost";


/*
DO NOT EDIT BELOW 
*/

$db = mysql_connect("$dbhost", "$dbuser", "$dbpass") or die('Script Could not connect to database');
mysql_select_db("$dbname",$db);
$query = "SELECT id,PortBase,servername,maxbitrate FROM servers ORDER by PortBase DESC";
$data = mysql_query($query);

function stop_server($port,$id,$srvname,$bitrate,$maxrate,$rootdir,$notify) {
mysql_query('UPDATE servers SET enabled="0" where PortBase="'.$port.'" AND id="'.$id.'"');
shell_exec("kill `cat $rootdir/servers/$port$srvname.pid`");
unlink("$rootdir/servers/$port$srvname.pid");
$message = "Server $srvname:$port stopped due to excessive bitrate of $bitrate.  Configured bitrate is $maxrate";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);
// Send
mail(''.$notify.'', 'Server '.$srvname.' on '.$port.' exceeded bitrate setting', $message);
}

while($result = mysql_fetch_row($data)){

$fp = @fsockopen("$serverhost", $result[1], $errno, $errstr, 30);
                if(!$fp){
                }
                if($fp) {
                fputs($fp,"GET /7.html HTTP/1.0\r\nUser-Agent: XML Reader(Mozilla Compatible)\r\n\r\n");
                while(!feof($fp)) {
                $dataset = fgets($fp, 1000);
                }
                fclose($fp);
                $dataset1 = $dataset;
                $headerinfo = ereg_replace("<body>.*","",$dataset);
                $dataset = ereg_replace(".*<body>", "", $dataset);
                $dataset = ereg_replace("</body>.*", ",", $dataset);
                $entries = explode(",",$dataset);
                $listener=$entries[0];
                $status=$entries[1];
                $listenerpeak = $entries[2];
                $maxlisteners=$entries[3];
                $totallisteners=$entries[4];
                $bitrate=$entries[5];
                $songtitel=$entries[6];

if($result[3] != ''){
		$id = $result[0];
		$port = $result[1];
		$srvname = $result[2];
		$max_rate = $result[3];
			if($bitrate > $max_rate){
				echo "$srvname port $port found to be in bitrate violation, stopping server, emailing admin\n";
				stop_server($port,$id,$srvname,$bitrate,$max_rate,$rootdir,$notify);
						}
			}else{
		echo "$bitrate found on server $result[2]\n";
			}
                }




}


?>
