<?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";
  if (strpos($record['table_name'], 'packet2023122') === false) continue;
    // Create a new index on the receiver_id
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_receiver_id_timestamp_idx;");
    echo 'Re-reate index on receiver_id on ' . $record['table_name'] . "... \r\n";
    pg_query($dbconn, "CREATE INDEX {$record['table_name']}_receiver_id_timestamp_idx ON {$record['table_name']} (receiver_id, timestamp);");
}

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