<?php

require __DIR__ . '/vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

/*

Reference:

----
CPU
----

idle cpu: vmstat | tail -1 | awk '{print $15}'
cpu: 100 - idle cpu

----------------------
Load Average (15 min)
----------------------

uptime | awk '{print $NF}'

-------
Memory
-------

total: free | tail -2 | head -1 | awk '{print $2}'
used: free | tail -2 | head -1 | awk '{print $3}'
result: used/total * 100

-----------
Disk Usage
-----------

df -h /dev/vda1 --output=pcent | tail -1 | sed 's/.$//'

*/

$idle_cpu = shell_exec('vmstat | tail -1 | awk \'{print $15}\'');
$cpu = 100 - (int)$idle_cpu;

$load_average = shell_exec('uptime | awk \'{print $NF}\'');

$total_memory = shell_exec('free | tail -2 | head -1 | awk \'{print $2}\'');
$used_memory = shell_exec('free | tail -2 | head -1 | awk \'{print $3}\'');
$memory_utilization = (int)((int)$used_memory / (int)$total_memory * 100);

$disk_usage = shell_exec('df -h /dev/vda1 --output=pcent | tail -1 | sed \'s/.$//\'');
$disk_usage = trim($disk_usage);

$server_name = $_SERVER['SERVER_NAME'];

$final_values = array($server_name, $cpu, $load_average, $memory_utilization, $disk_usage);
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://'.$_SERVER['HOST_URL'].'/api/customer/server',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => 'server_name='.$server_name.'&cpu='.$cpu.'&load_average='.$load_average.'&memory_utilization='.$memory_utilization.'&disk_usage='.$disk_usage,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'Content-Type: application/x-www-form-urlencoded'
  ),
));

$response = curl_exec($curl);
curl_close($curl);
