#!/usr/local/bin/perl
#########################################################################
#                               ISTP SOFTWARE
#                      Property of the U.S. Government
#                            NASA/GSFC/Code 560
#########################################################################
#
# UNIT NAME:  lzp_checkftp
#
# PURPOSE:  Scans FTP transfer log and identifies files for processing.
#
# INVOCATION METHOD:  lzp_checkftp [flags] [-a archive] path
#
# ARGUMENT LIST:
# NAME          TYPE                USE  DESCRIPTION
# ------------  ------------------  ---  -------------------------------
# flags         string               I   -v = enable verbose printing
#                                        -h = print syntax/usage
#                                        -a = specify archive directory
#
# path          string               I   Archive directory to save
#                                        copies of original data
#
# path          string               I   Top level directory to use  
#                                        to get begining of full path
#
# EXTERNAL FILE/RECORD REFERENCES:
# /usr/local/bin/perl shell script interpreter
#
# EXTERNAL VARIABLES:
# none
#
# EXTERNAL UNIT/MACRO/PROCEDURE/FUNCTION REFERENCES:
# none
#
# ABNORMAL TERMINATION CONDITIONS, ERROR MESSAGES:
#
# ASSUMPTIONS, CONSTRAINTS, RESTRICTIONS:
# none
#
# CHANGE HISTORY:
# AUTHOR           CHANGE-ID  RELEASE     DATE      DESCRIPTION OF CHANGE
# ---------------  ---------  ----------  --------  ---------------------
# K. Hogie         ISTP       R1.0B       11/18/97  Original code
# R. Wiechert      ISTP       R1.0C       01/02/98  Add archive directory
#                                                    and help function
# R. Wiechert      ISTP       R1.0D       01/28/98  Added diagnostic messages
# R. Wiechert      ISTP       R1.3        06/30/98  Standard option parsing
#                                                    and pass receipt time on
#
# NOTES:
# none
#
#########################################################################

require "getopts.pl";

@PROGN    = split( /\// , $0 ) ; # split program name
$PROGNAME = $PROGN[ -1 ] ; # get last field of program name
$ARCHIVE  = "-a " . $ENV{'HOME'} . "/archive" ; # default archive directory

if ( ! &Getopts( 'hva:' ) ) { $opt_h=1; } # sets opt_* for each option

if ( $opt_h ) { $HELP = "-h"; } #display help screen
if ( $opt_v ) { $VERBOSE = "-v"; } #enable verbose mode
if ( $opt_a ) { $ARCHIVE = "-a " . $opt_a; } #specify archive

if ( not "$ARGV[0]" or "$HELP" ) { print_help(); }
$CHKPATH = " " . $ARGV[0] ;

$FN = "/var/adm/xferlog" ;
$XX = open( IN, '<' . $FN ) ;
if( $XX <= 0 )
{
	# fatal error opening log file
	printf( STDERR "ERROR: lzp_checkftp: open(%s)\n", $FN ) ;
	exit( ) ;
}

while ( <IN> )
{
	if( /$CHKPATH/ and /cdrblks/ )
	{
		# parse each line of the logfile to extract filename, performance, status, etc
		$FIXED = substr( $_, 0, 24 ) ; # get initial fixed length info
		( $RNAME, $RMONTH, $RDAY, $RTIME, $RYEAR ) = split( " ", $FIXED ) ;
		$RTIME = "-l " . $RNAME . "," . $RMONTH . "," . $RDAY . "," . $RTIME . ",GMT," . $RYEAR ;

		$VAR   = substr( $_, 25) ; # get rest of string from current logfile line
		( $DUR, $HOST, $BYTES, $FILENAME, $BA, $FLAG, $DIR, $ACC, $USER, $SERV ) = split( " ", $VAR ) ;
		$RATE = $BYTES / $DUR / 1000 ; # calculate transfer rate

		# check to see if file still exists; still needs to be moved and processed
		if( $DIR ne "i" ) { next } # skip outgoing files
		$TT = open( TEST, $FILENAME ) ;
		if( $TT > 0 )
		{
			close( TEST ) ;
			$NEW_FILENAME = $FILENAME ;
			$NEW_FILENAME =~ s/cdrblks/blks/ ;	# change cdrblks to blks
			if( $VERBOSE )
			{
				printf( STDERR "\nFOUND DATA FILE...\n\n" ) ;
				printf( STDERR "Remote Hostname = %s\n", $HOST ) ;
				printf( STDERR " Local Filename = %s\n", $FILENAME ) ;
				printf( STDERR "  Time Received = %s\n", $FIXED ) ;
				printf( STDERR " Bytes Received = %d\n", $BYTES ) ;
				printf( STDERR "  Xfer Duration = %d\n", $DUR ) ;
				printf( STDERR "      Xfer Rate = %d\n", $RATE ) ;
				printf( STDERR "\nMOVING DATA FILE...\n\n" ) ;
				printf( STDERR "   Old Location = %s\n", $FILENAME ) ;
				printf( STDERR "   New Location = %s\n", $NEW_FILENAME ) ;
			}

			$MV = rename( $FILENAME, $NEW_FILENAME ) ;	# move file to new directory
			if( $MV != 1 )
			{
				# report error and continue with remaining files
				printf( STDERR "ERROR: lzp_checkftp: rename(%s)\n", $FILENAME ) ;
			}
			else
			{
				# process file and exit;  remaining files will wait until next time
				system( "/opt/local/bin/lzp_process -f $RTIME $VERBOSE $ARCHIVE $NEW_FILENAME" ) ;
				exit( ) ;
			}
		}
	}
}

sub print_help{
	print "\n";
	print "USAGE:     lzp_checkftp [-hv] [-a archive] path\n";
	print "\n";
	print "PURPOSE:   Scans FTP transfer logs for files to be processed\n";
	print "\n";
	print "OPTIONS:   -h     display help screen\n";
	print "           -v     enable verbose mode\n";
	print "           -a     specify archive directory\n";
	print "\n";
	print "SYNOPSIS:  The FTP transfer log /var/adm/xferlog is scanned for\n";
	print "           files located in subdirectories of the specified path.\n";
	print "           Pending files are moved to the FTP replay area from\n";
	print "           which they are archived and subsequently processed.\n";
	print "\n";
	print "NOTES:     This script is intended to run periodically as a cron\n";
	print "           job, one cron job per mission.  If no archive directory\n";
	print "           is specified, \$HOME/archive will be assumed by default.\n";
	print "           Use the command crontab -l to list a user's cron jobs.\n";
	print "\n";
	print "           The following example shows how to detect and process\n";
	print "           files appearing under /wind/ops (the default archive\n";
	print "           /wind/ops/archive is assumed):  lzp_checkftp /wind/ops\n";
	print "\n";
	exit( );
}
