#!/usr/bin/perl -w
use Getopt::Std;
my ($user, %nproc, %vsz, %rss, %pcpu, %pmem);
my $VERSION = '1.00';

format STDOUT_TOP =
NPROC USERNAME   SIZE    RSS     MEMORY TIME     CPU
.

format STDOUT =
@<<<< @<<<<<<<<< @#####M @#####M @####% @||||||| @####%
$nproc{$user},$user,$vsz{$user}/1024,$rss{$user}/1024,$pmem{$user},$time{$user},$pcpu{$user}
.

my %opts;
$Getopt::Std::STANDARD_HELP_VERSION = 1;
getopts('tcmun', \%opts) or die;

open PS, "/bin/ps -eo user,vsz,rss,pmem,time,pcpu |" or die;
while (<PS>) {
        next if /^USER/;
        /([\w-]+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+):(\d+):(\d+)\s+([\d.]+)/;
        $nproc{$1} ++;
        $vsz{$1} += $2; $rss{$1} += $3;
        $pmem{$1} += $4; $time{$1} += $5*3600+$6*60+$7;
        $pcpu{$1} += $8;
}
my @uSorted;
@uSorted = sort { $pcpu{$b} <=> $pcpu{$a} } keys %nproc if $opts{'c'};
@uSorted = sort { $pmem{$b} <=> $pmem{$a} } keys %nproc if $opts{'m'};
@uSorted = sort { $time{$b} <=> $time{$a} } keys %nproc if $opts{'t'};
@uSorted = sort keys %nproc if $opts{'u'};
@uSorted = sort { $nproc{$b} <=> $nproc{$a} } keys %nproc unless @uSorted;

foreach $user (@uSorted) {
        $_ = $time{$user};
        #$time{$user} = strftime("%H:%m:%S", localtime($_));
        $time{$user} = sprintf("%02i:", int($_/3600)); $_ = $_%3600;
        $time{$user}.= sprintf("%02i.", int($_/60)); $_ = $_%60;
        $time{$user}.= sprintf("%02i", $_);
        write;
}

__END__

=head1 NAME

 prstat - solaris compatible process status information

=head1 SYNOPSIS

 prstat [-t] [-c] [-n] [-u] [-m]

=head1 OPTIONS

=over 8

=item B<-t>
    Sort by time.

=item B<-c>
    Sort by cpu usage.

=item B<-m>
    Sort by memory usage.

=item B<-u>
    Sort by username.

=item B<-n>
    Sort by process count.

=back

=head1 DESCRIPTION

B<This program> is intended to re-create the process aggregation of solaris'prstat tool.

=cut
