#!/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 $lastswap = 0;
my $swapinindex = -1;
my $swapoutindex = -1;
open SAR, "sar -W |";
<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($swapinindex < 0 || $swapoutindex < 0) {
        for(my $i = 0; $i < @fields; $i++) {
          if($fields[$i] eq 'pswpin/s') {
            $swapinindex = $i;
          }
          if($fields[$i] eq 'pswpout/s') {
            $swapoutindex = $i;
          }
        }
      } elsif(@fields > $swapinindex && @fields > $swapoutindex) {
        $lastswap = $fields[$swapinindex] + $fields[$swapoutindex];
      }
    }
  }
}
close SAR;
die "Unable to find pswpin/s column\n" if $swapinindex < 0;
die "Unable to find pswpout/s column\n" if $swapoutindex < 0;

my $lastpage = 0;
my $pageinindex = -1;
my $pageoutindex = -1;
open SAR, "sar -B |";
<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($pageinindex < 0 || $pageoutindex < 0) {
        for(my $i = 0; $i < @fields; $i++) {
          if($fields[$i] eq 'pgpgin/s') {
            $pageinindex = $i;
          }
          if($fields[$i] eq 'pgpgout/s') {
            $pageoutindex = $i;
          }
        }
      } elsif(@fields > $pageinindex && @fields > $pageoutindex) {
        $lastpage = $fields[$pageinindex] + $fields[$pageoutindex];
      }
    }
  }
}
close SAR;
die "Unable to find pgpgin/s column\n" if $pageinindex < 0;
die "Unable to find pgpgout/s column\n" if $pageoutindex < 0;

printf "%.0f\n%.0f\n1\nSwap and Paging\n", $lastswap, $lastpage;
