<?php
// When possible read files instead of shell_exec or exec for efficiency

function strAppendVal(&$result, $val, $lblsng, $lblplural) {
    if($result != "") {
        $result .= ', ';
    }
    if($val == 1) {
        $result .= $val . ' ' . $lblsng;
    } else {
        $result .= $val . ' ' . $lblplural;
    }
}
// mimic uptime -p
function getUpTime() {
    $result = "";
    $tmp = file_get_contents("/proc/uptime");
    $items = preg_split('/\s+/', $tmp);
    $secs = intval($items[0]);
    $days = intval($secs / 86400);
    if($days > 0) {
        strAppendVal($result, $days, 'day', 'days');
        $secs -= ($days * 86400);
    }
    $hours = intval($secs / 3600);
    if($hours > 0) {
        strAppendVal($result, $hours, 'hour', 'hours');
        $secs -= ($hours * 3600);
    }
    $mins = intval($secs / 60);
    if($mins > 0 || $result == "") {
        strAppendVal($result, $mins, 'minute', 'minutes');
    }
    return $result;
}

function kbToHuman($kb) {
    $result = '';
    if(intval($kb) > 1048576) {
        $result = number_format((floatval($kb) / 1048576), 1) . 'Gi';
    } else if(intval($kb) > 1024) {
        $result = number_format((floatval($kb) / 1024), 1) . 'Mi';
    } else {
        $result = $kb . 'Ki';
    }
    return $result;
}

function getDevSubItems($usbDevPath, $devPaths, $id1, $id2) {
    $result = "";

    foreach($devPaths as $file) {
        if(strlen($file) > strlen($id1) && ( (substr($file, 0, strlen($id1)) == $id1) || (substr($file, 0, strlen($id2)) == $id2) )) {
            $prodfilepath = $usbDevPath . '/' . $file . '/product';
            if(file_exists($prodfilepath)) {
                $desc = file_get_contents($prodfilepath);
                $result .= "<br/>&nbsp;&nbsp;&nbsp;&nbsp;" . $desc;
            }
        }
    }
    return $result;
}

// Used = MemTotal - MemFree - Cached - SReclaimable - Buffers
function getMemInfo() {
    $result = [ '1', '2', '3', '4', '5', '6' ];
    $memtot = 0;
    $memfree = 0;
    $buffers = 0;
    $cached = 0;
    $sreclaim = 0;
    $fh = fopen("/proc/meminfo", 'r');
    if($fh !== false) {
       for($i = 0; $i < 25; $i++) {
          $line = fgets($fh);
          $items = preg_split('/\s+/', $line);
          if($i < 3) {
            $result[$i] = kbToHuman($items[1]);
          }

          if($items[0] == 'MemTotal:') {
             $memtot = intval($items[1]);
          } else if($items[0] == 'MemFree:') {
             $memfree = intval($items[1]);
          }  else if($items[0] == 'Buffers:') {
             $buffers = intval($items[1]);
          } else if($items[0] == 'Cached:') {
             $cached = intval($items[1]);
          } else if($items[0] == 'SReclaimable:') {
             $sreclaim = intval($items[1]);
          } else if($items[0] == 'Shmem:') {
             $result[4] = kbToHuman($items[1]);
          }
       }
       fclose($fh);
       $result[3] = kbToHuman($memtot - $memfree - $cached - $sreclaim - $buffers);
       $result[5] = kbToHuman($buffers + $cached + $sreclaim);
    }
    // Returns 0=MemTotal,1=MemFree,2=MemAvail,3=used,4=shared,5=buf/cache
    return $result;
}

$tzpath = realpath("/etc/localtime");
if(substr($tzpath, 0, 20) == '/usr/share/zoneinfo/') {
    $tz = substr($tzpath, 20);
    date_default_timezone_set($tz);
}

$uptm = getUpTime();
$datetm =  date("D M d  H:i:s T Y");

$temperature = file_get_contents('/sys/class/thermal/thermal_zone0/temp');
$tempval = $temperature / 1000;
$cpu = sys_getloadavg();
$num_cpus = 4;
$av1 = number_format($cpu[0] / $num_cpus * 100, 2, '.', '');
$av5 = number_format($cpu[1] / $num_cpus * 100, 2, '.', '');
$av15 = number_format($cpu[2] / $num_cpus * 100, 2, '.', '');

echo '<table class="table table-bordered table-hover table-sm" id="main-table">';
echo '<tr><th colspan="3">General Status</th></tr>';
echo '<tr><td colspan="2">Uptime</td><td>' . $uptm . '</td></tr>';
echo '<tr><td colspan="2">Date/time</td><td>' . $datetm . '</td></tr>';
echo '<tr><td colspan="2">Processor core temperature</td><td>' . $tempval . ' °C ';
// if(file_exists('/usr/share/825/log/t????-??-??.csv')) {
if(count(glob('/usr/share/825/log/t*')) > 0) {
    echo '&nbsp;&nbsp;<a href="tlog.php">log</a>';
}
echo '</td></tr>';
echo '<tr><td rowspan="3">CPU<br/>Load average</td><td>Last minute</td><td>' . $av1 . ' % </td></tr>';
echo '<tr><td>Last 5 minutes</td><td>' . $av5 . ' % </td></tr>';
echo '<tr><td>Last 15 minutes</td><td>' . $av15 . ' % </td></tr>';
echo '</table>';

$mem = getMemInfo();

echo '<table class="table table-bordered table-hover table-sm" id="main-table">';
echo '<tr><th colspan="6">RAM Memory</th></tr>';
echo '<tr><td align="right">Total</td><td align="right">Used</td><td align="right">Free</td><td align="right">Shared</td><td align="right">Cache</td><td align="right">Available</td></tr>';
echo '<tr><td align="right">' . $mem[0] . '</td><td align="right">' . $mem[3] . '</td><td align="right">' . $mem[1] . '</td><td align="right">' . $mem[4] . '</td><td align="right">' .  $mem[5]  . '</td><td align="right">' . $mem[2] . '</td></tr>';
echo '</table>';

exec('df -h', $df_buff, $return_val);

echo '<table class="table table-bordered table-hover table-sm" id="main-table">';
echo '<tr><th colspan="6">Storage Memory</th></tr>';
foreach( $df_buff as $line) {
    // echo "<br/>" . $line;
    $items = preg_split('/\s+/', $line);
    echo '<tr><td>' . $items[0] . '</td><td align="right">' . $items[1] . '</td><td align="right">' . $items[2] . '</td><td align="right">' . $items[3] . '</td><td align="right">' . $items[4] . '</td><td>' . $items[5] . '</td></tr>';
}
echo '</table>';

exec('ps -f --forest -u admin', $ps_buff, $return_val);
echo '<table class="table table-bordered table-hover table-sm" id="psTable">';
echo '<tr><th colspan="5">Process Status</th></tr>';
echo '<tbody>';
foreach( $ps_buff as $line) {
    // echo "<br/>" . $line;
    $items = preg_split('/\s+/', $line);
    $cmdpos = strrpos($line, ':');
    if($cmdpos > 0) {
        $cmd = substr($line, $cmdpos + 3);
        if(strlen($cmd) > 60) {
            $cmd = substr($cmd, 0, 60) . '...';
        }
        $slashpos = strpos($cmd, '\\_');
        if($slashpos > 0) {
            $tmp = '';
            for($n = 0; $n < $slashpos; $n++) {
                $tmp .= '&nbsp;&nbsp;';
            }
           $cmd = $tmp . $cmd;
        }
    } else {
        $cmd = $items[7];
    }
    echo '<tr><td align="right">' . $items[1] .  '</td><td align="right">' . $items[3] . '</td><td align="right">' . $items[4] . '</td><td align="right">' . $items[6] . '</td><td>' . $cmd . '</td></tr>';
}
echo '</tbody></table>';
?>
<script>

document.querySelector('#psTable').addEventListener('click', function(event) {
    //alert('clicked psTable');
    // Find the closest <tr> to the clicked element
    const row = event.target.closest('tr');

    if(row && row.cells.length >= 5 && row.rowIndex > 1) {
        const pid = row.cells[0].textContent;
        const cmd = row.cells[4].textContent;
        pos = cmd.lastIndexOf('/');
        if(pos >= 0) {
            newCmd = cmd.substr(pos + 1);
            if (confirm(`Kill process ${pid} ${newCmd}`) == true) {
                if (confirm(`Are you really sure you want to kill ${newCmd}`) == true) {
                    window.location.href = `diagnostics.php?killpid=${pid}&app=${newCmd}`;
                }
            }
        }
    }
});
</script>
<?php
$usbPaths = [ 'USB2,/sys/bus/usb/devices/1-1.4,', 'USB3-1,/sys/bus/usb/devices/2-1.1,/sys/bus/usb/devices/1-1.1', 'USB3-2,/sys/bus/usb/devices/2-1.2,/sys/bus/usb/devices/1-1.2', 'USB-C,/sys/bus/usb/devices/4-1,' ];

$usbDevPath = '/sys/bus/usb/devices';
$devPaths = scandir($usbDevPath);

echo '<table class="table table-bordered table-hover table-sm" id="main-table">';
echo '<tr><th colspan="2">USB Devices</th></tr>';
foreach($usbPaths as $usbPath) {
    $usbItems = explode(',', $usbPath);
    echo '<tr><td>' . $usbItems[0] . '</td>';
    $pathFound = '';
    $usb2 = 0;
    if(is_dir($usbItems[1])) {
        $pathFound = $usbItems[1];
    } else if(strlen($usbItems[2]) > 0 && is_dir($usbItems[2])) {
        $pathFound = $usbItems[2];
        $usb2 = 1;
    }
    if($pathFound != '') {
        $info = file_get_contents($pathFound . '/product');
        if($usb2 == 1) {
            $info = '*USB2* ' . $info;
        }
        $subitems = '';
        if($usbItems[0] == 'USB-C') {
            $subitems = getDevSubItems($usbDevPath, $devPaths, '4-1', '3-1');
        } else if($usbItems[0] == 'USB3-2') {
            $subitems = getDevSubItems($usbDevPath, $devPaths, '2-1.2', '1-1.2');
        } else if($usbItems[0] == 'USB3-1') {
            $subitems = getDevSubItems($usbDevPath, $devPaths, '2-1.1', '1-1.1');
        } else if($usbItems[0] == 'USB2') {
            $subitems = getDevSubItems($usbDevPath, $devPaths, '1-1.4', 'xxxxx');
        }
        if($subitems != '') {
            $info .= $subitems;
        }
        echo '<td>' . $info . '</td>';
    } else {
        echo '<td></td>';
    }
    echo '</tr>';
}
echo '</table>';
//echo '<img src="usbwebcam2.jpg?m=' . filemtime('usbwebcam2.jpg') . '">';

?>


