* @license Licensed under GNU General Public License v2.0. See file license.txt
 *
 * @todo in verbose mode state how many log files were rotated
 */
require 'autoload.php';
$cli = eZCLI::instance();
$script = eZScript::instance(array('description' => '...', 'use-session' => false, 'use-modules' => true, 'use-extensions' => true));
$script->startup();
$options = $script->getOptions('', '', array());
$script->initialize();
if ($script->verboseOutputLevel() > 0) {
    $cli->output("Rotating ezperformancelogger log files...");
}
$ini = eZINI::instance('ezperformancelogger.ini');
// std logs
if ($ini->variable('logfileSettings', 'RotateFiles') == 'enabled') {
    $logFile = $ini->variable('logfileSettings', 'FileName');
    eZPerfLoggerLogManager::rotateLogs(dirname($logFile), basename($logFile), 0, $ini->variable('logfileSettings', 'MaxLogrotateFiles'));
    if ($script->verboseOutputLevel() > 0) {
        $cli->output("Log files rotated");
    }
}
// csv logs
if ($ini->variable('csvSettings', 'RotateFiles') == 'enabled') {
    $logFile = $ini->variable('csvSettings', 'FileName');
    eZPerfLoggerLogManager::rotateLogs(dirname($logFile), basename($logFile), 0, $ini->variable('logfileSettings', 'MaxLogrotateFiles'));
    if ($script->verboseOutputLevel() > 0) {
        $cli->output("Csv files rotated");
    }
}
$script->shutdown();
$exclude = array();
if ($options['alsostatic'] == null) {
    // remove all known static paths - list taken from .htaccess
    /// @todo we should try to understand if we have to anchor regexp to url root (ie if we are in vhost mode)
    $exclude[] = '#.*/var/([^/]+/)?storage/images(-versioned)?/.*#';
    $exclude[] = '#.*/var/([^/]+/)?cache/(texttoimage|public)/.*#';
    $exclude[] = '#.*/design/[^/]+/(stylesheets|images|javascript)/.*#';
    $exclude[] = '#.*/share/icons/.*#';
    $exclude[] = '#.*/extension/[^/]+/design/[^/]+/(stylesheets|flash|images|lib|javascripts?)/.*#';
    $exclude[] = '#.*/packages/styles/.+/thumbnail/.*#';
    $exclude[] = '#.*/var/storage/packages/.*#';
}
if ($options['excludefilter'] !== null) {
    $exclude[] = '#' . str_replace('#', '\\#', $options['excludefilter']) . '#';
}
$ok = eZPerfLoggerLogManager::updateStatsFromLogFile($logFilePath, 'eZPerfLoggerApacheLogger', 'eZPerfLoggerUrlExtractorStorage', null, $exclude, true);
$stats = eZPerfLoggerUrlExtractorStorage::getStats();
/// @todo sort urls based on inverse access time / name / frequency
if ($options['sort'] == '' || $options['sort'] == 'count') {
    foreach ($stats as $key => $row) {
        $count[$key] = $row['count'];
        $url[$key] = $row['url'];
    }
    // Add $data as the last parameter, to sort by the common key
    array_multisort($count, SORT_DESC, $url, SORT_ASC, $stats);
}
$i = 0;
foreach ($stats as $idx => $data) {
    /// @todo shall we avoid printing empty lines?
    if ($options['data'] == '' || $options['data'] == 'count') {
        echo "[{$data['count']}] ";
$logFilePath = '';
$plIni = eZINI::instance('ezperformancelogger.ini');
$logTo = $plIni->variable('GeneralSettings', 'LogMethods');
if (in_array('apache', $logTo) && !in_array('logfile', $logTo)) {
    $logFileIni = eZINI::instance('logfile.ini');
    $logFilePath = $logFileIni->variable('AccessLogFileSettings', 'StorageDir') . '/' . $logFileIni->variable('AccessLogFileSettings', 'LogFileName');
} else {
    if (!in_array('apache', $logTo) && in_array('logfile', $logTo)) {
        $logFilePath = $plIni->variable('logfileSettings', 'FileName');
    } else {
        $cli->error("Cannot decide which log-file to open for reading, please enable either apache-based logging or file-based logging.");
        $script->shutdown(1);
    }
}
if ($logFilePath != '') {
    $cli->output("Parsing file " . $logFilePath);
    $storageClass = $plIni->variable('ParsingSettings', 'StorageClass');
    $excludeRegexps = $plIni->variable('ParsingSettings', 'ExcludeUrls');
    $ok = eZPerfLoggerLogManager::updateStatsFromLogFile($logFilePath, 'eZPerfLoggerApacheLogger', $storageClass, 'updateperfstats.log', $excludeRegexps);
    if ($ok === false) {
        $cli->output("Error parsing file {$logFilePath}. Please run script in debug mode for more info");
    } else {
        $cli->output("{$ok['counted']} lines containing data found");
    }
}
$dt = new eZDateTime();
$cli->output("Finished at " . $dt->toString() . "\n");
if ($script->verboseOutputLevel() > 0) {
    $cli->output("Perf counters have been updated\n");
}
$script->shutdown();
     }
     break;
 case 'fetch':
 default:
     if ($variable == '') {
         $cli->output("Error: you are using the ezmuninperflogger_ script as munin plugin. You should create symlinks named ezmuninperflogger_\$varname instead");
         $script->shutdown(-1);
     }
     if ($variable != 'pageviews' && !in_array($variable, $ini->variable('GeneralSettings', 'TrackVariables'))) {
         $cli->output("Error: '{$variable}' is not a tracked perf. variable");
         $script->shutdown(-1);
     }
     $logMethods = $ini->variable('GeneralSettings', 'LogMethods');
     if (in_array('csv', $logMethods)) {
         eZPerfLoggerMemStorage::resetStats();
         $ok = eZPerfLoggerLogManager::updateStatsFromLogFile($ini->variable('csvSettings', 'FileName'), 'eZPerfLoggerCSVStorage', 'eZPerfLoggerMemStorage', "muninplugin-{$variable}-csv.log", array('/^URL$/'));
         if ($samples = eZPerfLoggerMemStorage::getStatsCount()) {
             if ($variable != 'pageviews') {
                 $values = eZPerfLoggerMemStorage::getStats($variable);
                 //$values['avg'] = $values['total'] / $samples;
                 echo "{$variable}_tot.value {$values['total']}\n";
                 echo "{$variable}_min.value {$values['min']}\n";
                 echo "{$variable}_max.value {$values['max']}\n";
                 echo "pageviews.value {$samples}\n";
             } else {
                 echo "pageviews_count.value {$samples}\n";
             }
         } else {
             if ($variable != 'pageviews') {
                 // Either no logfile or no samples in range
                 // Slight difference between reporting 0 and U (unknown == null):