#!/usr/local/perl/bin/perl -w
#
# This script processes VIIRS images provided by CIMSS/SSEC.
#  RUN ON PX1 BY CRON TASK
#
# The input file name will have a form similar to:
#  SSEC_AWIPS_VIIRS-EAST_1KM_SVI01_20120203_0203.55779600
# This file arrives as a gzip-compressed netCDF file.
#
# Created by
# Jordan Gerth
# Last modified September 20, 2012
# 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="/processVIIRS.log";
open (LOGVIIRS, ">/data/logs/fxa/$datedir$logfile");

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

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

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

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

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

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

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

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

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

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

# Determine AWIPS filename, additional directories
$nextus0 = index($shortname,'_',12);
$dir0 = substr($shortname,11,$nextus0-11);
$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,8);

# Place file into location for it to be viewed using the D-2D
print LOGVIIRS `mv $filename $viirsdir$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 LOGVIIRS `testFileNotify k $prodkey $filenmout`;
}

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

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

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