#!/usr/local/bin/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-2013 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__ . '/../../ingo/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__);
}
$prefs_storage = $injector->getInstance('Ingo_Factory_Storage')->create('Prefs');
$sql_storage = $injector->getInstance('Ingo_Factory_Storage')->create('Sql');

/* Rules to convert. */
$rules = array(Ingo_Storage::ACTION_FILTERS,
               Ingo_Storage::ACTION_BLACKLIST,
               Ingo_Storage::ACTION_WHITELIST,
               Ingo_Storage::ACTION_VACATION,
               Ingo_Storage::ACTION_FORWARD,
               Ingo_Storage::ACTION_SPAM);

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

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

    $registry->setAuth($user, array());
    $session->set('ingo', 'current_share', ':' . $user);

    foreach ($rules as $rule) {
        $filter = $prefs_storage->retrieve($rule);
        if ($rule == Ingo_Storage::ACTION_FILTERS) {
            $new_filter = $sql_storage->retrieve(Ingo_Storage::ACTION_FILTERS, true);
            foreach ($filter->getFilterList() as $rule) {
                $new_filter->addRule($rule);
                echo '.';
            }
        }
        try {
            $sql_storage->store($filter);
        } catch (Horde_Exception $e) {
            $cli->writeln();
            $cli->message($e->getMessage(), 'cli.error');
        }
    }
    $cli->writeln($cli->green('done'));
}
