<?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..
    echo 'Update ' . $record['table_name'] . "... \r\n";

    pg_query($dbconn, "
    WITH subquery AS (
        SELECT p.id, p.course, ROUND(p.speed / 1.852) AS speed FROM ".$record['table_name']." p WHERE p.source_id = 2 AND p.speed IS NOT NULL
    )
    UPDATE ".$record['table_name']."_weather
    SET wind_speed = subquery.speed * .44704
    FROM subquery
    WHERE wind_speed != (subquery.speed * .44704) AND packet_id = subquery.id;
    ");
}

// Drop old to_call column
//echo 'Drop column ' . $record['table_name'] . ".to_call... \r\n";
//pg_query($dbconn, "ALTER TABLE packet DROP to_call;");

echo "Nothing to do...\r\nProcessing complete!\r\n";
