#!/usr/bin/php
<? // ( -*- php -*- this makes emacs users happy too? )
/*
 Network Interface Statistics Collection Agent v2.5
 by Brett Baugh

 This script collects counts from the localhost /proc/net/dev file
 and stuffs them into the "stats" table of the database.

 I recommend running this script with "nohup collect &", either
 as root or whomever you gave write permission to for the "stats"
 database, either from one of your startup scripts (rc.local, etc)
 or just from the command line if you don't feel like collecting
 statistics *all* the time.

 Almost all configuration for this script is done in the database.
 If you change something in the configuration, you don't have to kill
 and restart this script in order for it to take effect; it reads
 the config every cycle. There are two exceptions...

 */

//---------------------------------------------------------------------------------//
// If you want to run this from crontab instead of as a daemon, change the
// $runasdaemon variable to anything but "y", and then add a crontab job for it.
$runasdaemon="y";
// Where to put your temporary SQL queries cache file.
// Don't use the same file as the one the "snmp_collect" script is using!
// BEWARE if you have one of those demon-possessed systems that nukes /tmp on every reboot.
$cache_file="/tmp/nisca-local_sql_cache.txt";
//---------------------------------------------------------------------------------//

set_time_limit(0);
$skip_load=1; // tells functions.php to not automatically load all the config
              // variables and interfaces; this collector has its own way.
$inhibit_html=1; // tells functions.php to just DIE if this is being run from a browser.
require_once("/etc/nisca/nisca.conf");
require_once($location["functions"]);
require_once($location["cfunctions"]);

if ($argc > 1) {
  $debug="y";
} else {
  unset($debug);
  write_pid($location["local_pidfile"]);
}

while (1==1) {
  if ($debug) { $start_overall=getmicrotime(); }
  load_globals();
  load_local_ifs();
  if (! $all=file($statsfile)) {
    echo "Couldn't open $statsfile\n";
    die;
  }
  $stamp=time();
  foreach($all as $line) {
    $tmp=preg_match('/\s*(\S+)\s*:/', $line, $regs);
    if (in_array($regs[1], $local_interfaces)) {
      if ($debug) {
        $start_host=getmicrotime();
        echo "Doing interface \"{$regs[1]}\"... ";
      }
      $tmp=preg_match('/^\s*([\w\d]+)\s*:\s*(\d+)[\s]*(.*)$/', $line, $regs);
      $tmp=preg_split('/\s+/', $regs[3]);
      $id=$if_id[$local_hostname][""][$regs[1]];
      if ($id=="") {
        $sq="select id from stats_ifs where (hostname like '$local_hostname' AND " .
             "community='' AND if_name like '{$regs[1]}')";
        $res=dosql2($sq);
        if (mysql_num_rows($res) > 0) {
          $id=mysql_result($res,0,"id");
        } else {
          if ($debug) {
            echo "\n  New interface detected; adding... ";
          }
          $sq="insert into stats_ifs values(0, '$local_hostname', '', '{$regs[1]}')";
          $res=dosql2($sq);
          $id=mysql_insert_id();
          if ($debug) {
            echo "new id is $id.\n";
          }
        }
        $if_id[$local_hostname][""][$regs[1]]=$id;
      }
      $sq="insert into stats values($id, {$regs[2]}, {$tmp[0]}, {$tmp[1]}, {$tmp[2]}, {$tmp[7]}, {$tmp[8]}, {$tmp[9]}, {$tmp[10]}, $stamp)";
      if ($debug) {
        $tmp=formattime(getmicrotime()-$start_host);
        echo "done ($tmp).\nI would have sent this SQL query now:\n\n$sq\n\n";
      } else {
        if (dosql2($sq)==FALSE) {
          $sql_cache[]="$sq\n";
        } else {
          send_cache();
        }      
      }
    }
  }
  if ($debug) {
    $tot=formattime(getmicrotime()-$start_overall);
    echo "Entire collection cycle took $tot.\n";
    unset($tot);
  }
  save_cachefile(); 
  if ($runasdaemon != "y") {
    break;
  }
  if ($debug) {
    echo "Sleeping for $delay seconds...\n" .
         "-----------------------------------------------------------------------\n\n";
    flush();
  } else {
  }
  sleep($delay);
}
unlink($location["local_pidfile"]);
?>
