#!/usr/bin/env php
<?php
/**
 * This script converts all dates from the user's timezone to UTC.
 */

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

/* Prepare DB stuff. */
$db = $injector->getInstance('Horde_Db_Adapter');
try {
    $result = $db->selectAll('SELECT event_title, event_id, event_creator_id, event_start, event_end, event_allday, event_recurenddate, event_exceptionoriginaldate FROM ' . $conf['calendar']['params']['table'] . ' ORDER BY event_creator_id');
} catch (Horde_Db_Exception $e) {
    echo $e->getMessage() . "\n";
    exit;
}

$stmt = 'UPDATE kronolith_events SET event_start = ?, event_end = ?, event_recurenddate = ?, event_exceptionoriginaldate = ? WHERE event_id = ?';

/* Confirm changes. */
if (!isset($argv[1]) || $argv[1] != '--yes') {
    $answer = $cli->prompt('Running this script will convert all existing events to UTC. This conversion is not reversible. Is this what you want?', array('y' => 'Yes', 'n' => 'No'));
    if ($answer != 'y') {
        exit;
    }
}

/* Loop through all events. */
$creator = null;
$utc = new DateTimeZone('UTC');
echo "Converting events for:\n";
$timezone = new DateTimeZone(date_default_timezone_get());
foreach ($result as $row) {
    if ($row['event_allday']) {
        continue;
    }
    if ($row['event_creator_id'] != $creator) {
        if (!is_null($creator)) {
            echo "$count\n";
        }
        $prefs = $injector->getInstance('Horde_Core_Factory_Prefs')->create('horde', array(
            'cache' => false,
            'user' => $row['event_creator_id']
        ));

        $timezone = $prefs->getValue('timezone');
        if (empty($timezone)) {
            $timezone = date_default_timezone_get();
        }
        $timezone = new DateTimeZone($timezone);
        $creator = $row['event_creator_id'];
        $count = 0;
        echo $creator . ': ';
    }
    $start = new DateTime($row['event_start'], $timezone);
    $start->setTimezone($utc);
    $end = new DateTime($row['event_end'], $timezone);
    $end->setTimezone($utc);
    if (!empty($row['event_recurenddate'])) {
        $recur_end = new DateTime($row['event_recurenddate'], $timezone);
        $recur_end->setTimezone($utc);
    }
    if (!empty($row['event_exceptionoriginaldate'])) {
        $eod = new DateTime($row['event_exceptionoriginaldate'], $timezone);
        $eod->setTimezone($utc);
    }

    try {
        $db->update($stmt, array(
            $start->format('Y-m-d H:i:s'),
            $end->format('Y-m-d H:i:s'),
            !empty($row['event_recurenddate']) ? $recur_end->format('Y-m-d H:i:s') : null,
            !empty($row['event_exceptionoriginaldate']) ? $eod->format('Y-m-d H:i:s') : null,
            $row['event_id']));
    } catch (Horde_Db_Exception $e) {
        echo $e->getMessage() . "\n";
        exit;
    }
    $count++;
}
echo "$count\n";
