#!/usr/bin/perl
#
# aoserv-mrtg - MRTG configured by the AOServ Platform.
# Copyright (C) 2016, 2018, 2026  AO Industries, Inc.
#     support@aoindustries.com
#     7262 Bull Pen Cir
#     Mobile, AL 36695
#
# This file is part of aoserv-mrtg.
#
# aoserv-mrtg is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# aoserv-mrtg 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with aoserv-mrtg.  If not, see <http://www.gnu.org/licenses/>.
#   

my $maxCPU = 0;
my %idles = ();
my %systems = ();
my $cpuindex = -1;
my $systemindex = -1;
my $idleindex = -1;
open SAR, "sar -P ALL |";
<SAR>;
<SAR>;
while(<SAR>) {
  chomp;
  if(!/^Average:/ && !/LINUX RESTART/) {
    if(substr($_, 8, 3) eq ' AM' || substr($_, 8, 3) eq ' PM') {
      $_ = substr($_, 11);
    } else {
      $_ = substr($_, 8);
    }
    my @fields = split ' ';
    if (@fields) {
      if($cpuindex < 0 || $systemindex < 0 || $idleindex < 0) {
        for(my $i = 0; $i < @fields; $i++) {
          if($fields[$i] eq 'CPU') {
            $cpuindex = $i;
          }
          if($fields[$i] eq '%system') {
            $systemindex = $i;
          }
          if($fields[$i] eq '%idle') {
            $idleindex = $i;
          }
        }
      } elsif(@fields > $cpuindex && @fields > $systemindex && @fields > $idleindex) {
        my $cpu = $fields[$cpuindex];
        if($cpu ne 'CPU') {
          $systems{$cpu} = $fields[$systemindex];
          $idles{$cpu} = $fields[$idleindex];
          if($cpu > $maxCPU) {
            $maxCPU = $cpu;
          }
        }
      }
    }
  }
}
close SAR;
die "Unable to find CPU column\n" if $cpuindex < 0;
die "Unable to find %system column\n" if $systemindex < 0;
die "Unable to find %idle column\n" if $idleindex < 0;
$format = "%.0f\n%.0f\n1\nCPU Idletime\n";
$numCPUs = $maxCPU + 1;
if($numCPUs >= 6 && ($numCPUs & 1) == 0) {
  # Any number of even CPUs of six or more
  $sum1 = 0;
  $sum2 = 0;
  for(my $i = 0; $i < ($numCPUs / 2); $i++) {
    $sum1 = $sum1 + $idles{$i};
    $sum2 = $sum2 + $idles{$numCPUs / 2 + $i};
  }
  printf $format, 100 - $sum1 / ($numCPUs / 2), 100 - $sum2 / ($numCPUs / 2);
} elsif(exists $idles{3}) {
  # Four CPUs
  printf $format, 100 - ($idles{0} + $idles{1}) / 2, 100 - ($idles{2} + $idles{3}) / 2;
} elsif(exists $idles{1}) {
  # Two CPUs
  printf $format, 100 - $idles{0}, 100 - $idles{1};
} elsif(exists $idles{'all'}) {
  # One CPU
  printf $format, $systems{'all'}, 100 - $idles{'all'};
} else {
  die "Unknown number of CPUs";
}
