#!/bin/bash

# Process Terra MODIS Level 0 data to Level 1B
# Test data obtained from http://eosfes1.ssec.wisc.edu/data/MODIS
# Liam.Gumley@ssec.wisc.edu 2014/04/08

# Check arguments
if [ $# -ne 1 ]; then
  echo "Usage: run_terra_modis_level1.bash terra_pds_file"
  exit 1
fi

# Get arguments
terra_pds_file=$1

# Check for input PDS file
if [ ! -r $terra_pds_file ]; then
  echo "Input PDS file not found: "$terra_pds_file
  exit 1
fi

#------------------------------------------------------------------------------
# SET UP
#------------------------------------------------------------------------------

# Set up OCSSW
export OCSSWROOT=$DBVM_HOME/apps/ocssw
export OCSSW_DEBUG=0 
source $OCSSWROOT/OCSSW_bash.env

#------------------------------------------------------------------------------
# PROCESS TERRA MODIS
#------------------------------------------------------------------------------

echo ""
echo "Starting Terra MODIS processing at "$(date)

# Terra MODIS Level 1A extraction
echo modis_L1A.py --log --verbose --mission=T --startnudge=5 --stopnudge=5 $terra_pds_file 
modis_L1A.py --log --verbose --mission=T --startnudge=5 --stopnudge=5 $terra_pds_file 
if [ $? -ne 0 ]; then
  echo "Error in Terra MODIS L1A processing"
  exit 1
fi

# Get name of new Level 1A file
level1a_file=$(ls -1t T*.L1A_LAC | head -1)

# Terra MODIS geolocation
echo modis_GEO.py --log --verbose --enable-dem --entrained --disable-download $level1a_file 
modis_GEO.py --log --verbose --enable-dem --entrained --disable-download $level1a_file 
if [ $? -ne 0 ]; then
  echo "Error in Terra MODIS GEO processing"
  exit 1
fi

# Get name of new geolocation file
geo_file=$(ls -1t T*.GEO | head -1)

# Terra MODIS calibration
echo modis_L1B.py --log --verbose $level1a_file $geo_file
modis_L1B.py --log --verbose $level1a_file $geo_file
if [ $? -ne 0 ]; then
  echo "Error in Terra MODIS L1B processing"
  exit 1
fi

# Get name of new L1B 1KM file
level1b_file=$(ls -1t T*.L1B_LAC | head -1)

# Terra MODIS destriping
export DESTRIPE_ROOT=$DBVM_HOME/apps/destripe/destripe
$DESTRIPE_ROOT/run_modis_destripe.csh terra $level1b_file
if [ $? -ne 0 ]; then
  echo "Error in Terra MODIS destripe processing"
  exit 1
fi

#------------------------------------------------------------------------------
# CLEAN UP AND EXIT
#------------------------------------------------------------------------------

rm $level1a_file *.pcf Log*
exit 0

