<?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)
{
    echo "Checking {$record['table_name']}...\r\n";
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_pkey;");
    echo 'Recreate primary index ' . $record['table_name'] . "... \r\n";
    pg_query($dbconn, "ALTER TABLE {$record['table_name']} ADD CONSTRAINT {$record['table_name']}_pkey PRIMARY KEY (\"id\");");

    echo "Checking {$record['table_name']}_ogn...\r\n";
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_ogn_pkey;");
    echo 'Recreate primary index ' . $record['table_name'] . "_ogn... \r\n";
    pg_query($dbconn, "ALTER TABLE {$record['table_name']}_ogn ADD CONSTRAINT {$record['table_name']}_ogn_pkey PRIMARY KEY (\"id\");");

    echo "Checking {$record['table_name']}_path...\r\n";
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_path_pkey;");
    echo 'Recreate primary index ' . $record['table_name'] . "_path... \r\n";
    pg_query($dbconn, "ALTER TABLE {$record['table_name']}_path ADD CONSTRAINT {$record['table_name']}_path_pkey PRIMARY KEY (\"id\");");

    echo "Checking {$record['table_name']}_telemetry...\r\n";
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_telemetry_pkey;");
    echo 'Recreate primary index ' . $record['table_name'] . "_telemetry... \r\n";
    pg_query($dbconn, "ALTER TABLE {$record['table_name']}_telemetry ADD CONSTRAINT {$record['table_name']}_telemetry_pkey PRIMARY KEY (\"id\");");

    echo "Checking {$record['table_name']}_weather...\r\n";
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_weather_pkey;");
    echo 'Recreate primary index ' . $record['table_name'] . "_weather... \r\n";
    pg_query($dbconn, "ALTER TABLE {$record['table_name']}_weather ADD CONSTRAINT {$record['table_name']}_weather_pkey PRIMARY KEY (\"id\");");

    echo "... series complete..\r\n\n";
}

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