<?php

echo pht('Ensuring project names are unique enough...') . "\n";
$table = new PhabricatorProject();
$table->openTransaction();
$table->beginReadLocking();
$projects = $table->loadAll();
$slug_map = array();
foreach ($projects as $project) {
    $project->setPhrictionSlug($project->getName());
    $slug = $project->getPhrictionSlug();
    if ($slug == '/') {
        $project_id = $project->getID();
        echo pht("Project #%d doesn't have a meaningful name...", $project_id) . "\n";
        $project->setName(trim(pht('Unnamed Project %s', $project->getName())));
    }
    $slug_map[$slug][] = $project->getID();
}
foreach ($slug_map as $slug => $similar) {
    if (count($similar) <= 1) {
        continue;
    }
    echo pht("Too many projects are similar to '%s'...", $slug) . "\n";
    foreach (array_slice($similar, 1, null, true) as $key => $project_id) {
        $project = $projects[$project_id];
        $old_name = $project->getName();
        $new_name = rename_project($project, $projects);
        echo pht("Renaming project #%d from '%s' to '%s'.\n", $project_id, $old_name, $new_name);
        $project->setName($new_name);
    }
}