#!/usr/local/perl/bin/perl -w
#
# This script processes AVHRR images provided by CIMSS/SSEC.
#  RUN ON PX1 BY CRON TASK
#
# The input file name will have a form similar to:
#  SSEC_AWIPS_AVHRR_CONUSONE_1KM_ST02_20100203_0203.7209
# This file arrives as a gzip-compressed netCDF file.
#
# Created by
# Jordan Gerth
# Last modified July 2, 2010
# CIMSS/SSEC - Madison, Wisconsin
# http://www.ssec.wisc.edu/~jordang
# jordang@ssec.wisc.edu
#
# Acknowledgements
# Sincere gratitude is extended to
# Kim Licitar
# Information Technology Officer
# Milwaukee/Sullivan, Wisconsin
# Kim.Licitar@noaa.gov

# Create a system to log results of this script
$datedir=`date -u +%Y%m%d`;
chomp $datedir;
$logfile="/processAVHRR.log";
open (LOGAVHRR, ">/data/logs/fxa/$datedir$logfile");

# Record initiation time
print LOGAVHRR "Started ";
print LOGAVHRR `date`;
print LOGAVHRR "\n";

# Set directory where all incoming data will go
$tempdir="/data/fxa/sat/SBN/netCDF/LOCAL/AVHRR/temp/";
# Set base directory where the data will end up
$avhrrdir="/data/fxa/sat/SBN/netCDF/LOCAL/AVHRR/";

# Get data files from ldad account on ls1
print LOGAVHRR `scp -qr ldad\@ls1:/data/ldad/AVHRR/SSEC* $tempdir`;

# Clean up ls1 directory
print LOGAVHRR `ssh ldad\@ls1 rm -rf /data/ldad/AVHRR/SSEC*`;

# Create an array of all the files in temporary directory
@avhrrfiles=<$tempdir*_AWIPS_AVHRR_*.*>;

# Only run loop when files are ready to be processed
if ($#avhrrfiles >= 0) {

# Use array to process each file
foreach $filename (@avhrrfiles) {

# Indicate the attempt to process
print LOGAVHRR "Processing $filename";
print LOGAVHRR "\n";

# Add proper suffix and gunzip file
$filenmgz = "$filename".".gz";
print LOGAVHRR `mv $filename $filenmgz`;
print LOGAVHRR `gunzip $filenmgz`;

# Remove directory structure from file name
use File::Basename;
$shortname = basename($filename,"");

# Determine AWIPS filename, additional directories
$nextus0 = index($shortname,'-',18);
if ( $nextus0 < 0 ) {
$nextus0 = index($shortname,'_',18);
}
$dir0 = substr($shortname,17,$nextus0-17);
if ( $nextus0 > 0 ) {
$nextus0 = index($shortname,'_',18);
}
$nextus1 = index($shortname,'_',$nextus0+1);
$dir1 = substr($shortname,$nextus0+1,$nextus1-$nextus0-1);
$nextus2 = index($shortname,'_',$nextus1+1);
$dir2 = substr($shortname,$nextus1+1,$nextus2-$nextus1-1);
$periloc = index($shortname,'.');
$filenmout = substr($shortname,$nextus2+1,$periloc-$nextus2-1);
$prodkey = substr($shortname,$periloc+1,4);

# Place file into location for it to be viewed using the D-2D
print LOGAVHRR `mv $filename $avhrrdir$dir0/$dir1/$dir2/$filenmout`;

# Force the notificationServer to recognize the new file and
# update the time stamp for the image in the AWIPS menu system
print LOGAVHRR `testFileNotify k $prodkey $filenmout`;
}

} else {
print LOGAVHRR "No files found to process...aborted\n";
}

# Just in case, remove any files in temporary directory
print LOGAVHRR `rm -rf $tempdir*`;

# Close and exit
close (LOGAVHRR);
exit(0);
