#!/usr/bin/php -q
<?PHP
/* Copyright 2005-2023, Lime Technology
 * Copyright 2012-2023, Bergware International.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */
?>
<?
$docroot ??= ($_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp');
require_once "$docroot/webGui/include/ColorCoding.php";

$last  = "\e[0m";
$color = ['text' => $last, 'error' => "\e[91m", 'warn' => "\e[93m", 'system' => "\e[96m", 'array' => "\e[92m", 'login' => "\e[95m"];
$call  = ['tail','docker','grep'];

if (!in_array($argv[1]??'',$call)) exit;

$dummy = array_shift($argv);
$files = array_pop($argv);
array_multisort(array_map('filemtime',($logs = glob($files,GLOB_NOSORT))),SORT_ASC,$logs);
if (empty($logs)) $logs = [$files];

foreach ($color as $cat => $val) echo $val,$cat,$last,"  "; echo "\n\n";
foreach ($logs as $log) {
  $cmd = popen(implode(' ',$argv).' '.escapeshellarg($log),'r');
  while (($line = fgets($cmd))!==false) {
    $lead = $last;
    foreach ($match as $type) foreach ($type['text'] as $text) if (preg_match("/$text/i",$line)) {
      $lead = $color[$type['class']];
      break 2;
    }
    echo $lead,rtrim($line,"\n"),$last,"\n";
  }
  pclose($cmd);
}
?>
