#!/usr/bin/perl
use Time::Local;

BEGIN
  {
  $ENV{LD_LIBRARY_PATH}="LD_LIBRARY_PATH:/data/starfs1/libs/netcdf-4.2/lib:/data/starfs1/libs/hdf5-1.8.7/lib";
  }


# This script copies data from multiple AIRS granule files into an ADDF

print "\n";
print "Processing the AIRS (version 6) data\n";
print "\n";
system "date";
print "\n\n";


$source_dir = "/data/data065/nprovs/source/data_transfer/airs/version6";
$raw_data_dir = "/data/data065/nprovs/data/matchup/DailyFiles_incoming/raw_data/airs";
$nprovs_dir = "/data/data065/nprovs/data/matchup/DailyFiles_incoming";


chdir $raw_data_dir;

$addf_file_name = "airs_version6.addf";
$addf_file = $raw_data_dir . "/" . $addf_file_name;


# Remove all files that are currently in the raw data directory

#@files = glob "$raw_data_dir/"."*";

#foreach $file (@files)
#  {
#  unlink $file;
#  }



#-------------------------------------------------------------------------
# Calculate the date of the data to be processed. By default, this
# is usually yesterday. To override, replace $data_date with the
# date in the form YYYYMMDD

$data_day = time();
$data_day -= (1 * 86400);

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($data_day);
$year += 1900;
$mon++;
$sec = 0;
$min = 0;
$hour = 0;
$wday = 0;
#$yday = 0;
$isdst = 0;

# Increment the julian day to make it go from 1 to 365
$yday++;

$date_to_process = sprintf("%4d%02d%02d", $year, $mon, $mday);

printf("Date to be processed:  %d   Julian day: %d\n\n", $date_to_process, $yday);



#-------------------------------------------------------------------------
# Transfer the data from the NASA site

$wget = sprintf("wget --load-cookies ~/.urs_cookies --save-cookies ~/.urs_cookies --auth-no-challenge=on --keep-session-cookies --level=1 -r -nH -nd -np -A hdf https://discnrt1.gesdisc.eosdis.nasa.gov/data/Aqua_AIRS_NRT/AIRS2SUP_NRT.006/%d/%03d/", $year, $yday);

printf("%s\n", $wget);

#system $wget;



#-------------------------------------------------------------------------
# Process each AIRS file

printf("Processing the AIRS files\n");


@airsfiles = glob "$raw_data_dir/AIRS*.hdf";

foreach $file (@airsfiles)
  {
  printf("Processing file:  %s\n", $file);

  symlink $addf_file, "out.file" or warn "Cannot link $addf_file to out.file";

  #system "$source_dir/swath_read " . $file;
  system "$source_dir/AIRStoADDF.x " . $file;

  unlink "out.file" or warn "Cannot unlink the out.file";
  }


# Move the file to the incoming daily directory

system ("mv $addf_file $nprovs_dir/$addf_file_name");

# end of file
