#!/usr/bin/perl

our $VERSION = "0.0.0";
$VERSION = eval $VERSION;

use Modern::Perl;
use Getopt::Long 2.39;
use File::Basename qw(basename);

# application context
my $app = { };

# anonymous pod2usage sub
my $pod2usage = sub {
    require Pod::Usage;
	Pod::Usage::pod2usage(@_);
};

BEGIN {
    # set alarm to kill script if it takes too long to finish
    $SIG{ALRM} = sub { die "" };
    alarm 60;
}

END {
    say "ERROR: " . $app->{error} if $app->{error};

    # cancel alarm
    alarm 0;
}


### Main Processing Section ###

MAIN:
{
    # parse command line
    parse_cmdline(@ARGV);

    # get memory usage
    my $mem_usage = get_memory_usage();

    # print cacti string
    print hash2cacti($mem_usage);
}


### Subroutines ###

sub parse_cmdline {
    my @argv = @_;

    # option parser
    my $parser = Getopt::Long::Parser->new;
    $parser->configure('no_ignore_case');

    # option specifications
    my %opts;
    my @specs = (
        "debug",                    # optional, debug
        "help|h",                   # optional, help info
        "manual|m",                 # optional, complete manual
        "version|V",                # optional, version info
    );
	
    # parse options
    $pod2usage->(
        -verbose => 0,
        -exitval => 2,
        -message => " ",
    ) unless $parser->getoptionsfromarray(\@argv, \%opts, @specs);

    print_version() if $opts{version};
    print_manual()  if $opts{manual};
    print_help()    if $opts{help};

    # store args and opts in context
    $app->{args} = \@argv;
    $app->{opts} = \%opts;

    return 1;
};

sub get_memory_usage {
    # determine operating system
    my $OS = $^O;
    debug("Operating system: $OS");

    if ($OS eq 'linux') {
        return get_linux_memory_usage();
    }

    $app->{error} = "Unsupported operating system: $OS";
    exit(1);
}

sub get_linux_memory_usage {
    my $meminfo = "/proc/meminfo";
    my %meminfo = ();

    my $file = new IO::File($meminfo) or $app->{error} = "Couldn't open $meminfo" and exit(1);
    while (my $line = $file->getline()) {
        chomp($line);
        debug($line);

        if ($line =~ m/^(\S+):\s+(\S+) (\S+)/ ) {
            $meminfo{$1} = $2;
        }
    }
    $file->close;

    my $avail_real = $meminfo{MemTotal}  - $meminfo{MemFree } - $meminfo{Buffers} - $meminfo{Cached};
    my $used_real  = $meminfo{MemTotal}  - $avail_real        - $meminfo{Buffers} - $meminfo{Cached};
    my $used_swap  = $meminfo{SwapTotal} - $meminfo{SwapFree};
	
    # return hash ref containing memory usage
    return {
          usedReal => $used_real,
          usedSwap => $used_swap,
         availReal => $avail_real,
         totalReal => $meminfo{MemTotal},
         memCached => $meminfo{Cached  },
        memBuffers => $meminfo{Buffers },
	};
}

sub hash2cacti {
    my $href = shift;
    my $result;

    $result = join(" ", map { "$_:$href->{$_}" } sort keys %$href);
	$result = "CACTI | $result\n" if $app->{opts}{debug};

    return $result;
}

sub print_version {
    say STDERR basename($0) . " v" . main->VERSION();
    exit(0);
}

sub print_manual {
    alarm 0;
    $pod2usage->(
        -verbose => 2,
        -exitval => 1,
    );
};

sub print_help {
    $pod2usage->(
        -verbose => 0,
        -exitval => 1,
    );
};

sub debug {
    my $string = shift;
    say "DEBUG | $string" if $app->{opts}{debug};
}

__END__


=head1 NAME

mem2cacti - Query memory usage for Cacti

=head1 SYNOPSIS

B<mem2cacti> [options]

=over 2

=item Options:

  -h --help       Help info
  -m --manual     Manpages
  -V --version    Version info
  -d --debug      Debugging

=back

See `mem2cacti --manual` for the full documentation.

=head1 DESCRIPTION

This program queries memory statistics for this host. The output is formatted to use with Cacti.

=head1 OPTIONS

=over 4

=item B<-h, --help>

Displays a brief summary of mem2cacti's options.

=item B<-m, --manual>

Displays mem2cacti's full documentation.

=item B<-V, --version>

Display the version of mem2cacti.

=item B<-d, --debug>

Displays debug information.

=back

=head1 AUTHOR

Jurgen van den Hurk, E<lt>jvdhurk@tilburguniversity.eduE<gt>

=head1 LICENSE AND COPYRIGHT

Copyright 2017 Tilburg University. All rights reserved.

This program is free software; you may redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut