#!/usr/bin/perl

die "Troppi parametri in input" if($#ARGV > 0);
my $OPTION = shift || "-c";
die "Argomento $OPTION non valido, provare con -c o -m \n" if ($OPTION ne "-c" && $OPTION ne "-m");

my $column_index = 8;
$column_index = 9 if ($OPTION eq "-m");
 
my @file = qx{top -n 1 -b | tail -n +7};

# Ordinare in maniera decrescente gli utenti che usano più memoria/cpu
my %utentiConsumi_hash;

for(@file) {
	@colonne = split(' ', $_);
	if($colonne[1] =~ m/USER/)
	{
		print "$colonne[1] --- $colonne[$column_index]\n";
		open($log_file, ">>", "top_stat.log") || die ("Cannot open file !");
		print $log_file "$colonne[1] --- $colonne[$column_index]\n";
		close $log_file;
		next;
	}
	$utentiConsumi_hash{$colonne[1]} += $colonne[$column_index];
}

# Ordinamento hash
open($log_file, ">>", "top_stat.log") || die ("Cannot open file !");
foreach $key ( sort { ($utentiConsumi_hash{$b} <=> $utentiConsumi_hash{$a}) || ($a cmp $b)} keys %utentiConsumi_hash ) {
	print "$key --- $utentiConsumi_hash{$key}% \n";
	print $log_file "$key --- $utentiConsumi_hash{$key}% \n";
}

print $log_file "#"x20;
print $log_file "\n";
close $log_file;