<?php

require dirname(dirname(__FILE__)) . "/bootstrap.php";

$config = parse_ini_file(ROOT . '/../config/backend.ini', true);

if (is_array($config) && isset($config['bootstrap']))
{
    $databaseconfig = $config['bootstrap'];

    if (!isset($databaseconfig['username']))
    {
        $databaseconfig['username'] = get_current_user();
    }

    $dbconn = pg_pconnect(
      sprintf(
          'dbname=%s host=%s port=%s user=%s password=%s',
          $databaseconfig['database'],
          $databaseconfig['host'],
          $databaseconfig['port'],
          $databaseconfig['username'],
          $databaseconfig['password']
      )
    );

    if ($dbconn === false) die('Could not connect DB!');
} else {
  die('Invalid DB Config!');
}


$res = pg_query($dbconn,
"SELECT table_name
  FROM information_schema.tables
   WHERE table_schema='public'
     AND table_type='BASE TABLE'
     AND table_name LIKE 'packet20______';");

while (($record = pg_fetch_assoc($res)) !== false)
{
    // Update Fields..
    $count = 0;
    echo 'Processing ' . $record['table_name'] . "... \r\n";
    $res2 = pg_query($dbconn, "SELECT id, raw FROM {$record['table_name']} WHERE addresse IS NULL AND raw ILIKE '%::BLN%';");
    while (($packet = pg_fetch_assoc($res2)) !== false)
    {
      $msg = explode('>', $packet['raw'], 2);
      if (sizeof($msg) > 1)
      {
        $parts = explode(':', $msg[1]);
        $addresse = trim($parts[2]);
        if (strlen($addresse) <= 9)
          pg_query($dbconn, "UPDATE {$record['table_name']} SET addresse = '{$addresse}' WHERE id = {$packet['id']};");
        else echo "Skipping malformed addresse: $addresse \r\n";
        ++$count;
      }
    }

    echo "$count records updated, table complete.\r\n";
}
echo "Nothing to do...\r\nProcessing complete!\r\n";
