#!/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/publish.php";

$method  = $argv[1]??'';
$plugins = explode('*',$argv[2]??'');
$nchan   = $argv[$argc-1] == 'nchan'; // console or nchan output
$call    = ['plg' => 'plugin', 'xml' => 'language', '' => 'language'];

function write(...$messages){
  global $nchan;
  if ($nchan) {
    foreach ($messages as $message) {
      publish('plugins', $message,1,false);
    }
  } else {
    foreach ($messages as $message) echo $message;
  }
}

foreach ($plugins as $plugin) {
  if (!$plugin || (!$cmd = $call[pathinfo($plugin,PATHINFO_EXTENSION)])) continue;
  $line = '';
  $pluginArg = $method == "update" ? basename($plugin) : $plugin;
  $run = popen("$cmd $method $pluginArg",'r');
  while (!feof($run)) {
    $line .= fgetc($run);
    if (!empty($line) && in_array($line[-1],["\r","\n"])) {write($line); $line = '';}
  }
  pclose($run);
  write("\n");
}
if ($nchan) write('_DONE_','');
?>
