#!/usr/bin/php -q
<?PHP
/* Copyright 2005-2024, Lime Technology
 * Copyright 2012-2024, Bergware International.
 * Copyright 2014-2021, Guilherme Jardim, Eric Schultz, Jon Panozzo.
 *
 * 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/Wrappers.php";
require_once "$docroot/plugins/dynamix.docker.manager/include/DockerClient.php";
// this command will set the $notify array
extract(parse_plugin_cfg('dynamix', true));

// Multi-language support
$_SERVER['REQUEST_URI'] = "scripts";
$login_locale = _var($display,'locale');
require_once "$docroot/webGui/include/Translations.php";

exec('pgrep --ns $$ docker', $pid);
if (count($pid) == 1) exit(0);

$DockerClient = new DockerClient();
$DockerTemplates = new DockerTemplates();

foreach ($argv as $arg) {
  switch ($arg) {
  case '-v'   : $DockerTemplates->verbose = true; break;
  case 'check': $check = true; break;
  case 'nonotify': $nonotify = true; break;}
}

if (!isset($check)) {
  echo " Updating templates... ";
  $DockerTemplates->downloadTemplates();
  echo " Updating info... ";
  $DockerTemplates->getAllInfo(true);
  echo " Done.";
} else {
  $script = "$docroot/webGui/scripts/notify";
  $var    = (array)@parse_ini_file("/var/local/emhttp/var.ini");
  $server = strtoupper(_var($var,'NAME','tower'));
  $output = _var($notify,'docker_notify');
  $info   = $DockerTemplates->getAllInfo(true);
  foreach ($DockerClient->getDockerContainers() as $ct) {
    $name  = $ct['Name'];
    $image = $ct['Image'];
    if ($info[$name]['updated'] == "false") {
      $updateStatus = is_file($dockerManPaths['update-status']) ? json_decode(file_get_contents($dockerManPaths['update-status']),true) : [];
      $new = str_replace('sha256:', '', $updateStatus[$image]['remote']);
      $new = substr($new, 0, 4).'..'.substr($new, -4, 4);
      if ( ! isset($nonotify) ) {
        $event = str_replace("&apos;","'",_("Docker")." - $name [$new]");
        $subject = str_replace("&apos;","'",sprintf(_('Notice [%1$s] - Version update %2$s'),$server,$new));
        $description = str_replace("&apos;","'",sprintf(_("A new version of %s is available"),$name));
        exec("$script -e ".escapeshellarg($event)." -s ".escapeshellarg($subject)." -d ".escapeshellarg($description)." -i ".escapeshellarg("normal $output")." -l '/Docker' -x");
      }
    }
  }
}
exit(0);
?>
