#!/usr/bin/env php
<?php
/**
 * Converts a user's filter rules from the preferences storage backend to the
 * new SQL storage backend that has been added in Ingo 1.2.
 *
 * Usage: ingo-convert-prefs-to-sql < filename
 * Filename is a file that contains a list of users, one username per line.
 * The username should be the same as how the preferences are stored in
 * the preferences backend (e.g. usernames may have to be in the form
 * user@example.com).
 *
 * Copyright 2006-2017 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file LICENSE for license information (ASL).  If you
 * did not receive this file, see http://www.horde.org/licenses/apache.
 *
 * @author   Jan Schneider <jan@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/apache ASL
 * @package  Ingo
 */

$baseFile = __DIR__ . '/../lib/Application.php';
if (file_exists($baseFile)) {
    require_once $baseFile;
} else {
    require_once 'PEAR/Config.php';
    require_once PEAR_Config::singleton()
        ->get('horde_dir', null, 'pear.horde.org') . '/ingo/lib/Application.php';
}
Horde_Registry::appInit('ingo', array('cli' => true));

/* Initialize storage backends. */
if ($conf['storage']['driver'] != 'sql') {
    $cli->fatal('You need to configure an SQL storage backend in Ingo\'s configuration', __FILE__, __LINE__);
}
$p_storage = $injector->getInstance('Ingo_Factory_Storage')->create('Prefs');
$sql_storage = $injector->getInstance('Ingo_Factory_Storage')->create('Sql');

/* Update each user. */
while (!feof(STDIN)) {
    $user = fgets(STDIN);
    $count = 0;
    $user = trim($user);
    if (empty($user)) {
        continue;
    }

    echo 'Converting filters for user: ' . $user;

    $prefs_storage->clearCache();
    $sql_storage->clearCache();
    $injector->getInstance('Horde_Core_Factory_Prefs')->clearCache();
    $registry->setAuth($user, array());
    $session->set('ingo', 'current_share', ':' . $user);

    foreach ($p_storage as $val) {
        $val->uid = ($val instanceof Ingo_System_Rule)
            ? $sql_storage->getSystemRule(get_class($val))
            : '';

        try {
            $sql_storage->updateRule($val);
            echo '.';
        } catch (Horde_Exception $e) {
            $cli->writeln();
            $cli->message($e->getMessage(), 'cli.error');
        }
    }
    $cli->writeln($cli->green('done'));
}
