#!/usr/bin/env php
<?php
/**
 * Script to run a Horde_LoginTasks task and/or system task.
 *
 * Usage: horde-run-task -a [app] -t [taskname] -u [username]
 *   Taskname is the name of the file in the application's SystemTask/Task
 *   directory without the .php extension - this script will automatically
 *   build the full class name.
 *
 * Copyright 2010-2013 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
 *
 * @author   Michael Slusarz <slusarz@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package  Horde
 */

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

$c = new Console_Getopt();
$argv = $c->readPHPArgv();
array_shift($argv);
$options = $c->getopt2($argv, 'a:t:u:');
if ($options instanceof PEAR_Error) {
    $cli->fatal($options->getMessage());
    exit;
}

foreach ($options[0] as $val) {
    switch ($val[0]) {
    case 'a':
        $app = $val[1];
        break;

    case 't':
        $taskname = $val[1];
        break;

    case 'u':
        $username = $val[1];
        break;
    }
}

if (empty($app)) {
    $cli->fatal('Missing argument to -a.');
    exit;
}

if (empty($taskname)) {
    $cli->fatal('Missing argument to -t.');
    exit;
}

if (empty($username)) {
    $cli->fatal('Missing argument to -u.');
    exit;
}

$registry->setAuth($username, array());
$registry->pushApp($app, array('check_perms' => false));

$class = $app . '_LoginTasks_SystemTask_' . $taskname;
if (!class_exists($class)) {
    $class = $app . '_LoginTasks_Task_' . $taskname;
    if (!class_exists($class)) {
        $cli->fatal('Could not find task "' . $taskname . '".');
    }
}

$ob = new $class();
if (($ob instanceof Horde_LoginTasks_SystemTask) && $ob->skip()) {
    $cli->message('System task was skipped.', 'cli.warning');
} else{
    if ($ob instanceof Horde_Core_LoginTasks_SystemTask_Upgrade) {
        $ob->forceUpgrade();
    } else {
        $ob->execute();
    }
    $cli->message('Completed task.', 'cli.success');
}
