#!/usr/bin/perl

# qpeek:  Peek into a job's output spool files
# Copyright 2001, Ohio Supercomputer Center
#
# Usage:  qpeek [options] JOBID
#
# Options:
#   -c      Show all of the output file ("cat", default)
#   -h      Show only the beginning of the output file ("head")
#   -t      Show only the end of the output file ("tail")
#   -f      Show only the end of the file and keep listening ("tail -f")
#   -#      Show only # lines of output
#   -e      Show the stderr file of the job
#   -o      Show the stdout file of the job
#   -?      Display help

$tool="cat";
$numlines="";
$suffix="OU";
$spool="/var/spool/torque/spool";
$host="oscbw";

while ( $ARGV[0] =~ /^-.*/ )
  {
    if ( $ARGV[0] eq "-c" )
      {
        $tool="cat";
      }
    elsif ( $ARGV[0] eq "-f" )
      {
        $tool="tail -f";
      }
    elsif ( $ARGV[0] eq "-h" )
      {
        $tool="head";
      }
    elsif ( $ARGV[0] eq "-t" )
      {
        $tool="tail";
      }
    elsif ( $ARGV[0] =~ /^-[0-9]+$/ )
      {
        $numlines=$ARGV[0];
      }
    elsif ( $ARGV[0] eq "-e" )
      {
        $suffix="ER"
      }
    elsif ( $ARGV[0] eq "-o" )
      {
        $suffix="OU"
      }
    elsif ( $ARGV[0] eq "-?" || $ARGV[0] eq "-help" )
      {
        print STDERR <<EOF;
qpeek:  Peek into a job's output spool files

 Usage:  qpeek [options] JOBID

 Options:
   -c      Show all of the output file ("cat", default)
   -h      Show only the beginning of the output file ("head")
   -t      Show only the end of the output file ("tail")
   -f      Show only the end of the file and keep listening ("tail -f")
   -#      Show only # lines of output
   -e      Show the stderr file of the job
   -o      Show the stdout file of the job (default)
   -?      Display this help message
EOF
        exit;
      }
    else
      {
        print STDERR "qpeek:  Unrecognized option $ARGV[0] ignored\n";
      }
    shift(@ARGV);
  }

$jobid=shift(@ARGV);
$jobid=~s/\.[A-z0-9.]+$//;
die "No jobid given!\n" if ( $jobid eq "" );

$node=&mothersuperior($jobid);
die "Job $jobid is not running!\n" if ( $node eq "" );

exec "rsh $node $tool $numlines $spool/$jobid.$host.$suffix\n";


sub mothersuperior
{
  local($jobid,$node);
  $jobid=$_[0];
  $node="";
  open(QSTAT,"qstat -f $jobid |");
  while ( <QSTAT> )
    {
      chop;
      if ( $_ =~ /exec_host/ )
        {
	  ($keyword,$node)=split(/=/);
	  $node=~s:/[0-9]+[A-z0-9/+]*::;
	}
    }
  $node;
}

