#!/usr/bin/perl -w
# Author: Theodore Zacharia
# V0.1: 04/10/2004 - Initial Release
#
# This script provides a template to start all other scripts with
# supports arguments being passed and multi-threaded functions
# Uses shell builtin function getopts
#
#

#
# Globals
#
use strict;
use vars qw(%opt $retv $argnum $outputdir $opmode);

my $unsafe_toshutdown = 0;

my $trace = 0;
my $myarg = "";

#****************************************************************************
# Sub Routines
#****************************************************************************

#
# Command line options processing
#
sub init()
{
	use Getopt::Std;
	my $opt_string = 'a:htT';
	getopts( "$opt_string", \%opt ) or usage();
	usage() if $opt{h};
}

sub setmyargs()
{
	# set output directory/prefix
	if ($opt{o})
	{
		$outputdir = $opt{o};
		if ($opt{v} || $opt{d}) {
			print "files will be written to the directory/prefix $outputdir\n";
		}
	}

	if ($opt{t}) {
		$trace = 1;
	} elsif ($opt{T}) {
		$trace = 2;
	}

	if ($opt{a})
	{
		$myarg = $opt{a} ;
		print "myarg = $opt{a}\n" ;
	}

	print STDERR "Trace mode ON.\n" if ( $trace == 1 );
	print STDERR "High Trace mode ON.\n" if ( $trace == 2 );
}

#
# Message about this program and how to use it
#
sub usage()
{
	print STDERR << "EOF";

    usage: $0 [-t|T] -[a myarg] files

EOF
    exit;
}

#----------------------------------------------------------------------------
# sig_handler
#       Signal catcher for the SIGTERM signal (amongst others).
#       This is generally raised by the user to stop us running.
#       Close all connections and die gracefully
#
# Parameters:   $signame        signal name (HUP, TERM, etc.)
#
# Returns:              Does not return.
#
#----------------------------------------------------------------------------
sub sig_handler
{
	my $signame = shift @_;


	# We could analyse the signal here and act according to type.
	# For now, everything causes a shutdown unless it is unsafe.

	if ($unsafe_toshutdown)
	{
		print "\nSorry ... I am writing a file and cannot shutdown right now \n";
		return;
	}

	print "\nBye from sig_handler with $signame\n";

	exit $retv;
}

# for simplicity use globals here


#****************************************************************************
# Main Routine
#****************************************************************************

$retv		= 99;
$outputdir	= "";

init();
setmyargs();


$argnum = $#ARGV + 1;
if ($argnum < 1)
{
	print "\nIncorrect number of arguments passed\n";
	usage();
}

# now, all remaining positional args are input files

my @files = (@ARGV);
my $error;

# establish the signal hanlder
$SIG{TERM} = \&sig_handler;
$SIG{QUIT} = \&sig_handler;
$SIG{INT} = \&sig_handler;
$SIG{STOP} = \&sig_handler;

if ($trace > 1) {
	my $datestring = localtime();
	print "Starting at $datestring \n";
	print "positional args: @files \n";
}


END { $? = $retv }