#!/usr/bin/php
<?php

$cookiepath = "/etc/tor/control_auth_cookie";
$controlport = 9051;


// Nothing to change down here...

$cmd = $argv['1'];

$cookie = file_get_contents($cookiepath);


if ($cmd == "config") {

	echo "graph_title Traffic\n";
	echo "graph_args --base 1000 \n";
	echo "graph_vlabel bits in (-) / out (+) per ${graph_period}\n";
	echo "graph_category network\n";

	echo "down.label Download\n";
        echo "down.type GAUGE\n";

        echo "up.label Upload\n";
	echo "up.type GAUGE\n";

	exit;

} elseif ($cmd == "autoconf") {

	$socket = fsockopen("tcp://127.0.0.1", $controlport);
	fputs($socket, "AUTHENTICATE \"".$cookie."\"\n");

	$buffer = fgets($socket, 1024);
	if (ereg("250", $buffer)) echo "Yes";
	else echo "No (".trim($buffer).")";

	fclose($socket);
	exit;


}



$socket = fsockopen("tcp://127.0.0.1", $controlport);

fputs($socket, "AUTHENTICATE \"".$cookie."\"\n");

$buffer .= fgets($socket, 4096);

if (!ereg("250", $buffer)) {
	echo "Unable to connect to Tor ControlPort (".$buffer.")";
	fclose($socket);
	exit;
} else {

	fputs($socket, "SETEVENTS bw\n");

	$buffer = fgets($socket, 1024);

        $buffer = fgets($socket, 1024);

        $bits = explode(" ", $buffer);

	echo "down.value ".($bits['2'] / 1024)."\n";

	echo "up.value ".($bits['3'] / 1024)."\n";

}

fclose($socket);

?>

