#!/bin/bash

# Example of a user script to be run within DBVM

# Get arguments
file_1km=$1
latmin=$2
lonmin=$3
latmax=$4
lonmax=$5
region=$6

# Get satellite/date/time (e.g., a1.06260.2057) from L1B 1KM file name (e.g., a1.06260.2057.1000m.hdf)
date_time=$(basename $file_1km | cut -d. -f1-3)

# Get pass year, day of year, time (e.g, 06 260 2057) from L1B 1KM file name (e.g., a1.06260.2057.1000m.hdf)
year=$(basename $file_1km | cut -c4-5)
jday=$(basename $file_1km | cut -c6-8)
time=$(basename $file_1km | cut -c10-13)

# Get HKM, QKM, and GEO file names
dir_1km=$(dirname $file_1km)
file_hkm=$dir_1km/$date_time.500m.hdf
file_qkm=$dir_1km/$date_time.250m.hdf
file_geo=$dir_1km/$date_time.geo.hdf

# Create soft links to standard MODIS filenames
mod021km=MOD021KM.A20$year$jday.$time.temp.hdf
mod02hkm=MOD02HKM.A20$year$jday.$time.temp.hdf
mod02qkm=MOD02QKM.A20$year$jday.$time.temp.hdf
mod03=MOD03.A20$year$jday.$time.temp.hdf
ln -f -s $file_1km $mod021km
ln -f -s $file_hkm $mod02hkm
ln -f -s $file_qkm $mod02qkm
ln -f -s $file_geo $mod03

# Create the HDFLook template file
echo "verbose" > temporary_template.txt
echo "clear_data" >> temporary_template.txt
echo "set_projection_to_geometry ProjectionTo=LINEAR PIXELSIZEXTO=250 PIXELSIZEYTO=250" >> temporary_template.txt
echo "set_image_rgb_composite Visible" >> temporary_template.txt
echo "set_misc_options BilinearPixel=Yes" >> temporary_template.txt
echo "set_input_hdf_file "$mod02qkm >> temporary_template.txt
tiff_file=$date_time.$region.250m.tif
echo "create_modis_geotiff_image FileName="$tiff_file" \\" >> temporary_template.txt
echo "  RGBMode=Log MinR=5.8 MaxR=9.4 MinG=5.8 MaxG=9.4 MinB=5.8 MaxB=9.4 \\" >> temporary_template.txt
echo "  LatitudeMin="$latmin" LongitudeMin="$lonmin" LatitudeMax="$latmax" LongitudeMax="$lonmax >> temporary_template.txt

# Run HDFLook
export HDFLOOKTMP=.
export HDFLOOKMAPS=$DBVM_HOME/apps/hdflook/MAPS
export PATH=$DBVM_HOME/apps/hdflook/LINUX_INTEL32:$PATH
HDFLook temporary_template.txt

# Convert 250 meter GeoTIFF to enhanced 250, 500, and 1000 meter JPEGS
convert -modulate 105,125,100 -gamma 1.2 -contrast -unsharp 0 -quality 90 $tiff_file $date_time.$region.250m.jpg &> /dev/null
convert -geometry 50% $date_time.$region.250m.jpg $date_time.$region.500m.jpg
convert -geometry 25% $date_time.$region.250m.jpg $date_time.$region.1000m.jpg

# Clean up
rm temporary_template.txt $mod021km $mod02hkm $mod02qkm $mod03 $tiff_file $tiff_file.met

exit 0

