#!/usr/bin/env php
<?php
/**
 * A script to migrate permissions from the Horde_DataTree backend to the
 * new (Horde 3.2+) native SQL Perms backend.
 */

$baseFile = dirname(__FILE__) . '/../../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') . '/lib/Application.php';
}
Horde_Registry::appInit('horde', array('cli' => true));

$dt = Horde_DataTree::factory($conf['datatree']['driver'], array('group' => 'horde.perms'));
$p = new Horde_Perms_Datatree(array('datatree' => $dt));

$query = '
INSERT INTO
    horde_perms (perm_id, perm_name, perm_parents, perm_data)
VALUES
    (?, ?, ?, ?)
';

$db = $injector->getInstance('Horde_Db_Adapter');

foreach ($p->getTree() as $id => $row) {
    if ($id == -1) {
        continue;
    }

    $object = $p->getPermissionById($id);
    echo $id . "\n";

    $parents = $object->datatree->getParentList($id);
    asort($parents);
    $parents = implode(':', array_keys($parents));

    $params = array($id, $object->name, $parents, serialize($object->data));
    $db->insert($query, $params);
}

echo "\nDone.\n";
