#!/usr/bin/perl
#: List most recent processes
#==============================================================================
# sburke@cpan.org
our $Last_Modified =' Time-stamp: "2016-10-04 17:08:35 MDT"';
our $VERSION= "2.01";  use strict;  use warnings;    #use  Carp::Always;
use constant DEBUG => 10;

my $Sorting_Method
  = "-start_time"  # default
;

#======================================================================

if( ( $ENV{'PERL_PS_SORTY'} || '' )
    =~ m/\A(\S+)\z/
) {
  $Sorting_Method = $1;
}
DEBUG > 10 and print "~~~HOW: $Sorting_Method\n\n";

#======================================================================

our $PS_Bin = "/bin/ps";
die "No $PS_Bin!?" unless $PS_Bin and -e $PS_Bin and -x $PS_Bin;

our(@PS_Switches) =(
   "-A",
   $Sorting_Method ? "--sort=$Sorting_Method" : (),
   "--format=pid,ruser,pcpu,pmem,time,cmd",
);

my $MAX_LINES = 10;
my $SPACE = 6;

$| = 1;
Main_Run();
exit;
#======================================================================

sub Set_Max_Lines {


  if(   ($ENV{'LINES'} || '')   =~
    qr<
        \A
          (
            \d{1,4}
          )
        \z
      >x
  ) {
    my $n = 0 + $1;
    $n = $n - $SPACE;
    if($n > 1) {
      $MAX_LINES = $n;
      return;
    }
  }


  if( ($ENV{TERMCAP} || '') =~ m/\b li\# (\d+) \b/x    ) {
    my $n = 0 + $1;
    $n = $n - $SPACE;
    if($n > 1) {
      $MAX_LINES = $n;
      return;
    }
 }

  # Else who knows what the lines are.  Leave it as default value.
  return;
}

#======================================================================

sub Main_Run { # where a command-line call starts.  All is in @ARGV

  shift @ARGV if @ARGV and $ARGV[0] eq '--';
  die "I take no arguments" if @ARGV;

  Set_Max_Lines();
  Run_PS();

  return;
}

#======================================================================

sub Run_PS {

  my $ps_pid = open my $PS, "-|", $PS_Bin, @PS_Switches;
  die "Can't open channel from $PS_Bin {@PS_Switches} - $!"
   unless $ps_pid;

  #DEBUG > 9 and print "PS pid = $$";

  my(@lines) = readline($PS);

  my($count) = 0;

 Line_From_PS:
  foreach my $line (@lines) {

    if( $line =~
       qr<
         \A 
	   \s*
	   (\d{1,10})   # PID.  (Surely can't be more than 10 digits!)
	   \s+
	 >x
    ) {
      my($the_pid) = $1 + 0;
      next Line_From_PS if $the_pid == $$ or $the_pid == $ps_pid;
    }
    print $line;
    ++$count;
    last Line_From_PS if $MAX_LINES and $count >= $MAX_LINES;
  }

}

#======================================================================

__END__
