<?php
/**
 * @copyright 2024 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

session_start();

if ($_SESSION['loggedtorspanel'] == true) {

 $stat1 = file('/proc/stat');

 sleep(1);

 $stat2 = file('/proc/stat');
 $info1 = explode(" ", preg_replace("!cpu +!", "", $stat1[0]));
 $info2 = explode(" ", preg_replace("!cpu +!", "", $stat2[0]));

 $dif = array();
 $dif['user'] = $info2[0] - $info1[0];
 $dif['nice'] = $info2[1] - $info1[1];
 $dif['system'] = $info2[2] - $info1[2];
 $dif['idle'] = $info2[3] - $info1[3];
 $dif['iowait'] = $info2[4] - $info1[4];
 $dif['irq'] = $info2[5] - $info1[5];
 $dif['softirq'] = $info2[6] - $info1[6];
 $dif['steal'] = $info2[7] - $info1[7];

 $totaltime = array_sum($dif);
 $totalidle = $dif['idle'] + $dif['iowait'];
 $totalusage = $totaltime - $totalidle;

 $cpu = array();
 $cpu['total'] = round(($totalusage * 100) / $totaltime, 1);
 $cpu['system'] = round(($dif['system'] * 100) / $totaltime, 1);

 echo json_encode($cpu);

} else {
      header("Location: panel-login.php");
}

?>