<?php

/************************************************************/
// Create or Update the vendor table in Management DB.
// The table is used in opengatemchk
//
// At installation, run to create vendor table
// After installation, run periodically to update vendor table.

// the database connection parameters might be modified.
// As this script should be used only by the administrators, 
// it should be protected by some access control method.
/************************************************************/

//connect to Management DB (* set proper parameters *)
$link = mysqli_connect("localhost", "root", "");
if (!$link) die('Cannot connect to DB.'.mysqli_error());

// select opengatem database
$db_selected = mysqli_select_db($link, 'opengatem');
if (!$db_selected) die('Cannot select DB.'.mysqli_error());

// create table if not exists
$sql = "CREATE TABLE IF NOT EXISTS nicvendors(oui CHAR(8), org TINYTEXT)";
mysqli_query($link, $sql);

// open oui list in IEEE site
// $fp = fopen("http://standards.ieee.org/develop/regauth/oui/oui.txt", "r");
$fp = fopen("./oui.txt", "r");
if(!$fp) die('Cannot connect to IEEE data');

// scan the download list
while (!feof($fp)) {

  // get one line
  $line = fgets($fp);

  // get oui(MAC-left-3bytes) and org(company name) from header line
  // such as "AB-CD-EF   (hex)   Foo-bar company"
  $pattern='/([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})\s*\(hex\)\s*(.*)$/';
  if(preg_match($pattern, $line, $matches)!=1) continue;
  $oui=$matches[1];
  $org=$matches[2];

  // replace AB-CD-EF to ab:cd:ef
  $oui = str_replace("-",":",$oui);
  $oui = strtolower($oui);

  // remove quotation and tab code
  $org = str_replace("\"", "", $org);
  $org = str_replace("\t", "", $org);

  // insert to db
  $sql = sprintf(
    'REPLACE INTO nicvendors (oui,org) VALUES( "%s", "%s")',
    $oui, $org);
  mysqli_query($link, $sql);

  // log to console
  print $oui." ".$org."<br>\n";
}
fclose($fp);
?>

