#!/usr/bin/php -q
<?PHP
/* Copyright 2005-2021, Lime Technology
 * Copyright 2012-2021, 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  = '/usr/local/emhttp';
require_once "$docroot/webGui/include/publish.php";

function my_scale($value, &$unit) {
  $units = [' ','Ki','Mi','Gi','Ti','Pi','Ei','Zi','Yi'];
  $size = count($units);
  $base = $value ? floor(log($value, 1024)) : 0;
  if ($base>$size) $base = $size-1;
  $value /= pow(1024, $base);
  $decimals = $value>=100 ? 0 : ($value>=10 ? 1 : (round($value*100)%100===0 ? 0 : 2));
  if (round($value,-1)==1000) {$value = 1; $base++;}
  $unit = $units[$base].'B';
  return number_format($value, $decimals, '.', $value>9999 ? ',':'');
}

while (true) {
  $now = time(); $i = 0;
  unset($dump);  $vtun = [];
  exec('wg show all dump',$dump);
  foreach ($dump as $row) {
    $row = preg_split('/\s+/',$row);
    if (count($row)>5) $vtun[] = $row[0].';'.($row[5] ? $now - $row[5] : 0).';'.my_scale($row[6],$unit)." $unit;".my_scale($row[7],$unit)." $unit";
  }
  publish('wireguard', implode("\0",$vtun));
  sleep(1);
}
?>