#!/usr/bin/perl
#
#
# Notes:
# provides cache status (the same way as cachectl status) but can run by apl


use strict;
use warnings;
use File::Basename qw(dirname);


# Load configuration (env may be emtpy on the start)
my $dirname = dirname(__FILE__);
open (ECF,"$dirname/../../base/etc/env.conf")     || die("Cannot read env.conf\n");
map {$ENV{$1}=$2 if /^(\w+)=(\S+)/} grep {/^\w+=\S+/} <ECF>;
close ECF;

# ------------------ VARS -----------------------
my $APL = $ENV{APL} || '/opt/sarch';
my $CMD = $ARGV[0];
my $RETVAL = 1;
my $CONFFILE = "$APL/cache/etc/cache.cfg";
my %CFG;

# ------------------ ROUTINES -------------------
sub read_conf {
    open CONF, $CONFFILE or return 0;
    %CFG = map {/^(\w+)=(\S+)/} grep {/^\w+=\S+/} <CONF>;
    close CONF;
    return 1;
}

sub get_status {
    my ($status, $total, $free) = ('off', 0, 0);
    open(DF, "/bin/df -Pm $CFG{MOUNT_POINT} |");
    while(<DF>) {
	if (/^\S+\s+(\d+)\s+\d+\s+(\d+)\s+\d+%\s+$CFG{MOUNT_POINT}/) {
	    ($status, $total, $free) = ('on', $1, $2, $3);
	    last;
	}
    }
    close DF;
    return wantarray ? ($status, $total, $free) : $status;
}

sub status {
    print "@{[get_status]}\n";
    $RETVAL = 0;
}


# ------------------ MAIN -----------------------
die "Unable to read configuration\n" unless read_conf;
die "Mount point doesn't exist\n" unless -d $CFG{MOUNT_POINT};
status;
exit $RETVAL;
