#!/bin/perl

# test_procedure
#
# test_procedure,v 1.4 2003/06/11 22:42:38 castalia Exp

# This program, which takes a filename from the command line, is designed
# to help test and exercise Conductor's treatment of stderr and stdout and
# its different ways to gauge success.

use English;
use Getopt::Long;
use strict;

my ($Command) = $0;

# Set autoflush to true so that stdout is flushed with each print, printf,
# and write.
$| = 1;

# Process the command line.
$GetOpt::Long::ignorecase = 1;
my ($STATUS, $MESSAGE, $ID) = (undef, undef, undef);
GetOptions (
	"s|status=i"		=>	\$STATUS,
	"m|message=s"		=>	\$MESSAGE,
	"i|id=s"			=>	\$ID
) or die "Usage: $0 [-status status] [-message message] [-id id] <filename>\n";

# Get the file name from the command line and open for reading.
my $filename = $ARGV[0] or die "$Command:  Filename required.\n$!";

$Command .= "($ID)"
	if $ID;

# Print the file to stdout.
open (INPUT_FILE, "< $filename") or die "$Command: Can't read $filename -\n$!";
print STDOUT "$Command O1: stdout $filename -\n";
while (<INPUT_FILE>)
	{print STDOUT "$Command O1 - $_";}
close (INPUT_FILE);

# Print it to stderr.
open (INPUT_FILE, "< $filename") or die "$Command: Can't read $filename -\n$!";
print STDERR "$Command E1: stderr $filename -\n";
while (<INPUT_FILE>)
	{print STDERR "$Command E1 - $_";}
close (INPUT_FILE);

# Print it to both.
open (INPUT_FILE, "< $filename") or die "$Command: Can't read $filename -\n$!";
print STDOUT "$Command O2: stdout $filename interleaved with stderr -\n";
print STDERR "$Command E2: stderr $filename interleaved with stdout -\n";
while (<INPUT_FILE>)
	{
	print STDOUT "$Command O2 - $_";
	print STDERR "$Command E2 - $_";
	}
close (INPUT_FILE);
	
END
{

# 	The END block is reached on a die, so this code will be executed
# 	even if there was an error. If $STATUS was successfully set by
# 	the Getopt, then that will be reported. Otherwise, Perl's own
# 	inherent exit statuses will be used. These seem to be the following:
# 
# 	0		No error.
# 
# 	2		Could not open the file.
# 
# 	255		Error in processing the arguments.
	
	if ($MESSAGE)
		{
		print STDOUT "$Command: Message follows -\n";
		print STDOUT $MESSAGE . "\n";
		}
	
	if ($STATUS)
		{
		print STDOUT "$Command: STATUS = $STATUS\n";
		$? = $STATUS;
		}
	print STDOUT "$Command: stdout end.\n";
	print STDERR "$Command: stderr end.\n";
}
