<?php

global $g_comp_database;

// Set migrationId
$migrationIdentifier = "pass_encryption";

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Updating encryption of passwords already done.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Start updating encryption of passwords.</span>';

    $dao = \isys_cmdb_dao::instance($g_comp_database);

    $sql = "SELECT isys_cats_person_list__user_pass AS hash, isys_cats_person_list__id AS entryId, isys_obj__id AS id, isys_obj__title AS title
        FROM isys_cats_person_list
        INNER JOIN isys_obj ON isys_obj__id = isys_cats_person_list__isys_obj__id
        WHERE isys_cats_person_list__user_pass != '';";

    $update = "UPDATE isys_cats_person_list
        SET isys_cats_person_list__user_pass = %s,
        isys_cats_person_list__unmigrated_password = 1
        WHERE isys_cats_person_list__id = %d
        LIMIT 1;";

    $persons = $dao->retrieve($sql);
    while ($person = $persons->get_row()) {
        $new_password = $dao->convert_sql_text(isys_helper_crypt::encryptPassword($person['hash']));

        $dao->set_autocommit(false);
        $dao->begin_update();
        if (!($dao->update(sprintf($update, $new_password, $person['entryId'])) && $dao->apply_update())) {
            $dao->cancel_update();
            $g_migration_log[] = '<span class="bold red">Migrating the password for "' . $person['title'] . '" (#' . $person['id'] . ') failed! Please check the logs.</span>';
            $migrationDone = false;
        } else {
            $g_migration_log[] = '<span class="indent">Migrated "' . $person['title'] . '" (#' . $person['id'] . ')!</span>';
        }
    }

    $g_migration_log[] = '<span class="bold">Migration finished!</span>';

    $this->migration_done($migrationIdentifier);
}
