<?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, "UPDATE {$record['table_name']} SET addresse = TRIM(to_call) WHERE (addresse IS NULL AND to_call IS NOT NULL AND LENGTH(TRIM(to_call)) < 11); ;");

    // Drop old to_call index
    echo 'Drop index ' . $record['table_name'] . "_to_call_idx... \r\n";
    pg_query($dbconn, "DROP INDEX IF EXISTS {$record['table_name']}_to_call_idx;");

    // Create a new indeox on the addresse
    echo 'Create index on addresse on ' . $record['table_name'] . "... \r\n";
    pg_query($dbconn, "CREATE INDEX IF NOT EXISTS {$record['table_name']}_addresse_idx ON {$record['table_name']} USING btree (addresse);");
}

// 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";
