#!/usr/local/bin/php
<?php
/**
 * $Horde: nag/scripts/migrate_to_datatree_driver.php,v 1.1.10.1 2005/01/03 12:25:44 jan Exp $
 *
 * This script pulls tasks from the nag database format and puts them into
 * the datatree driver.
 *
 * Copyright 2003-2005 Cronosys, LLC <http://www.cronosys.com/>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 */

@define('AUTH_HANDLER', true);
@define('HORDE_BASE', dirname(__FILE__) . '/../..');

// Do CLI checks and environment setup first.
require_once HORDE_BASE . '/lib/core.php';
require_once 'Horde/CLI.php';

// Make sure no one runs this from the web.
if (!Horde_CLI::runningFromCLI()) {
    exit("Must be run from the command line\n");
}

// Load the CLI environment - make sure there's no time limit, init
// some variables, etc.
Horde_CLI::init();

// Registry
$registry = &Registry::singleton();
$registry->pushApp('nag');
$conf = &$GLOBALS['conf'];

require_once 'Horde/DataTree.php';
$notification = &Notification::singleton();

$params = Horde::getDriverConfig('auth', $conf['auth']['driver']);
$auth = &Auth::singleton($conf['auth']['driver'], $params);

@define('NAG_BASE', dirname(__FILE__) . '/..');
require_once NAG_BASE . '/lib/Nag.php';
require_once NAG_BASE . '/lib/Driver.php';

require_once 'DB.php';

$params = $conf['storage']['params'];
$charset = $params['charset'];
$db = &DB::connect($conf['storage']['params']);
if (is_a($db,'PEAR_Error')) {
    die($db->getMessage());
}

$q = sprintf('SELECT * FROM %s;', $conf['storage']['params']['table']);
$qr = $db->getAll($q, DB_FETCHMODE_ASSOC);
if (is_a($qr, 'PEAR_Error')) {
    die($qr->getMessage());
}

// We just use the driver to get the datatree object, the user isn't
// important.
$driver = &Nag_Driver::singleton('foo');

foreach ($qr as $row) {
    $auth->setAuth($row['task_owner'], array());

    $obj = &new DataTreeObject(String::convertCharset($row['task_name'], $charset));
    $obj->set('uid', String::convertCharset($row['task_uid'], $charset));
    $obj->set('description', String::convertCharset($row['task_desc'], $charset));
    $obj->set('tasklist', $row['task_owner']);
    $obj->set('category', $row['task_category']);
    $obj->set('due', $row['task_due']);
    $obj->set('priority', $row['task_priority']);
    $obj->set('completed', $row['task_completed']);
    $obj->set('alarm', $row['task_alarm']);

    $result = $driver->_datatree->add($obj);
    if (is_a($result, 'PEAR_Error')) {
        var_dump($result);
        exit;
    }
}

$db->query(sprintf("DROP TABLE %s;\n", $conf['storage']['params']['table']));

echo "** Tasks successfully converted to DataTree driver! ***\n";
