#!/usr/bin/perl

###########################################################################
# ldadsport.pl
#
# DESCRIPTION: 
#
# Preprocessor for SPoRT files to work-around LDAD timeout. This script 
# unzips files and places them into the EDEX manual endpoint directory to be 
# ingested.  Originally written by Jason Burks at WFO HUN.
#
# USE:
#	$ ldadsport.pl <file name (with full path) of the *.gz file>
#
# MODIFICATIONS:
# 20121115: 	Major rewrite (Don Britton)
# 20140422:	Code clean-up (Kevin McGrath / NASA SPoRT)
#
# SPoRT CONTACTS:
#	Jason Burks (jason.e.burks@nasa.gov)
#	Kevin McGrath (kevin.m.mcgrath@nasa.gov)
#	Matt Smith (msmith@itsc.uah.edu)
#
###########################################################################
use Cwd 'abs_path';

# AWIPS II directory into which all sport files will be stored for ingest into
# EDEX.
$target_dir = "/awips2/edex/data/manual";

# Temporary AWIPS II location for retrieved files (where they'll be unzipped).
$tempdir = "/data/fxa/LDAD/tmp";

# Path to gunzip
$gunzip = "/bin/gunzip";

# Path to mv
$mv	= "/bin/mv";

#########################
# Generate log file if desired.  No logging is performed if $log is null.
#########################

# Set name and path of log file, if so desired.
#$log = "/data/local/ldatsport.log";

# Open log file if $log is set.
if ($log) { open(LOG, ">$log"); }

########################################
# Passed arguments from ldad have an arbitrary 
# 10-digit number appended which serves no purpose for us. Remove it.
# E.g.: /data/fxa/LDAD/tmp/sportlma_nalma_rfd_20110427_2130.gz.1353081112
########################################

# Grab passed argument
$ldad_filename = $ARGV[0];
chomp($ldad_filename);

if (! $ldad_filename) { exit; }

@items = split(/\//,$ldad_filename);
@dots = split(/\./,$items[-1]);
$filewithout = join(".",@dots[0..$#dots-1]);
$filebeforegunzip=$filewithout;
$fileaftergunzip=join(".",@dots[0..$#dots-2]);

#print "Incoming File: $ldad_filename\n";
#print "File name before unzipped: $filebeforegunzip\n";
#print "File name after unzipped: $fileaftergunzip\n";

if ($log) {
	print LOG "\n#############################\n";
	$scriptName	= abs_path($0);
	printf LOG "$scriptName was lauched at " . `date -u` . "\n";
	print LOG "* File passed: $ARGV[0]\n";
}

$mvcmd = "$mv $ldad_filename $tempdir/$filebeforegunzip";
print LOG "* Moving file to temp location via \`$mvcmd\`\n" if ($log);
`$mvcmd`;

$gunzipcmd = "$gunzip $tempdir/$filebeforegunzip";
print LOG "* Unzipping file via \`$gunzipcmd\`\n" if ($log);
`$gunzipcmd`;

$moveToEnd = "$mv $tempdir/$fileaftergunzip $target_dir/".$fileaftergunzip;
print LOG "* Moving file to EDEX manual endpoint for ingest via \`$moveToEnd\`\n" if ($log);
`$moveToEnd`;

if ($log) {
	print LOG "\n";
	print LOG "$scriptName completed at " . `date -u`;
	print LOG "#############################\n\n";
	close(LOG);
}

exit;
