# Perl module to add usage reporting to any program run from within a perl 
# wrapper
#
# Usage;
#	require 'usage.pm';
#
# (no further code is required in the calling script)
#
# SJM, 2.7.97
#
# Main ---------------------------------------------------------------------

BEGIN {
# Takes the project and program name, and returns the usage ID for this process
# Errors should happen silently and so not affect operation of the script 
# from which this is called

	use DBI;

# Configuration -------------------------------------------

	$db_database = 'inform';	# database name
	$db_user = 'usage';			# database username
	$db_pass = 'usage';			# database password
 	$ENV{'ORACLE_HOME'} = '/nfs/app/oracle/product/7.3.2';

# ---------------------------------------------------------

	chomp($u_acct = `whoami`);		# account name
	chomp($u_mach = `uname -n`);	# machine name
	$u_prog = $0;					# script name
	$u_args = join(' ',@ARGV);		# script arguments

	if ($dbh = DBI->connect( $db_database, $db_user, $db_pass, 'Oracle')) {
		$sth = $dbh->prepare("BEGIN usage_master.add_record(\'$u_acct\',\'$u_prog\',\'$u_mach\',\'$u_args\',:1); END;");
		$sth->bind_param_inout(1, \$u_id,10);
		$sth->execute|| die "$DBI::errstr";
		$sth->finish;
		$dbh->disconnect;
		$u_id;
	} else {

die "Could not log in to usage database";
 		$u_id = 0;
	}
}

END {
	&check_out($u_id);
}

# Subroutines --------------------------------------------------------------

sub check_out {
# Takes a usage ID and records in the database when this program terminated
# this will die if there are errors

	local($input_id) = @_;

	$dbh = DBI->connect( $db_database, $db_user, $db_pass, 'Oracle') || die "Could not log in to usage database";
	$sth = $dbh->prepare("BEGIN usage_master.upd_record(\'$input_id\'); END;");
	$sth->execute || die "$DBI::errstr";
	$sth->finish;
	$dbh->disconnect;
}

1;	# for perl
