#!/bin/bash -xv
# ./create_postATS_week.sh: Run all of the next bash scripts in order to produce the next week's time series.

# Determine which type of file to use
USAGE="Usage: $0 [clean/filter] [jpl/sopac/comb/combwm] - select source type to continue
        [reset] - delete all created files to rerun from t0"

# delete stale files in displGrid
clear_displGrid () {
    
    # # restore LateStationHor backup file for 2010
    # cat displGrid/LateStationHor_original.dat > displGrid/LateStationHor.dat
    # # LateStationUp can start out blank
    # cat '' > displGrid/LateStationUp.dat

    rm -f displGrid/Vdisp*.ps
    rm -f displGrid/*.grd
    rm -f displGrid/vunk*.dat
    rm -f displGrid/dunk*.dat
    rm -f displGrid/GPS_resid_*.dat
    rm -f GMT_CnDynDatumUp99-18.dat
    rm -f displGrid/*.bb
    rm -f displGrid/*.eps
    rm -f displGrid/*.ps

    rm -rf dynamic_datum/
    rm -rf transients/
}

# expand .tar and files into /neu subdirectory
# accept 1 argument: tar filename
expand_targz_neu () {
tarFolder=${1}

    # Strip .tar.gz extension and create neu subdirectory
    baseTarFolder=$(basename ${tarFolder} ".tar.gz")
    neuSubDir="${workingDir}/${baseTarFolder}/neu"

    echo "Extracting files from ${tarFolder}"
    echo "Into $neuSubDir"
    mkdir -p "${neuSubDir}"

    if [[ $(uname) == "Linux" ]]; then
        # Extract tar.gz from remote location to working directory
	      gunzip < "$tarFolder" > "${workingDir}/${baseTarFolder}".tar

        # Extract .Z files from tar into neu subdir
        tar -xf "${workingDir}/${baseTarFolder}".tar -C ${neuSubDir}

        # Unzip individual .Z station files
        for z in "${neuSubDir}"/*.Z; do
            gunzip "$z"
        done

	      # remove local .tar
        rm "${workingDir}/${baseTarFolder}".tar

    elif [[ $(uname) == "Darwin" ]]; then        
        # Extract .tar.gz to WNAM_* folder directly
        tar -zxf "${tarFolder}" -C "${workingDir}/${baseTarFolder}"

        # Unzip individual station files and place in neu subdir
        for z in "${workingDir}/${baseTarFolder}"/*.Z; do
            tar -zxf "${z}" -C "${neuSubDir}"
            rm $z
        done
    fi
}


if [[ $# -ne 1 && $# -ne 2 ]]; then
    echo "$USAGE"
    exit 1
elif [[ $1 == "reset" ]]; then
    echo
    echo "Are you sure? This will delete all files in the following directories:"
    echo
    echo `du -hs displGrid/dynamic_datum/`
    echo `du -hs displGrid/transients`
    echo
    # Double prompt user to confirm deletion
    select yn in "Yes" "No"; do
        case $yn in
            "Yes" ) echo "Last chance."
                  select yn in "Delete files" "Exit"; do
                      case $yn in
                        "Delete files" ) clear_displGrid; exit;;
                        "Exit" ) exit;;
                      esac
                  done;;
            "No" ) exit;;
        esac
    done;
else
    if [[ $1 != "clean" && $1 != "filter" || $2 != "jpl" && $2 != "sopac" && $2 != "comb" && $2 != "combwm" ]] ; then
        echo "Invalid arguments: $@"
        echo "$USAGE"
        exit 1
    fi
fi

###################
# Begin execution
# Find the latest tar in postATSDir and extract to workingDir
postATSDir=/archive/garner/measuresESESES_products/Timeseries/WesternNorthAmerica/
workingDir='.'

tarFolder=`find $postATSDir -maxdepth 1 -iname "WNAM_${1}_TrendNeuTimeSeries_${2}_*.tar.gz" | sort | tail -n 1 `
if [ -z "$tarFolder" ]; then
      echo "Failed to find tar.gz folder"
      exit 1
fi

expand_targz_neu $tarFolder

# Strip .tar.gz extension and postATSDir path
baseTarFolder=$(basename ${tarFolder} ".tar.gz")
expandedTarFolder="${workingDir}/${baseTarFolder}"

python3 reconstruct.py "$expandedTarFolder"
echo "Reconstruct completed"

./Predict_weeklyDispl_1stStep.com "${1}" "${2}"
echo "Predict part 1/2 done"

python3 predict2.py
echo "Predict part 2/2 done"

cd displGrid

# Only needs to be run when a new model is created
# cd ZengModel/ZS2017 
# gmt xyz2grd ucerf3_0.05_itrf_vn.dat -Gucerf3_0.05_itrf_vn.grd -R-125/-114/31/42 -I0.05/0.05 
# gmt xyz2grd ucerf3_0.05_itrf_ve.dat -Gucerf3_0.05_itrf_ve.grd -R-125/-114/31/42 -I0.05/0.05 
# cd ../../

echo "Building horizontal components" 
./dispGrid_dataBased_uptodate.com

echo "Building vertical component" 
./dispGrid_dataBased_uptodate_up.com

echo "Isolating this week's solution"
./isolate_week.sh

echo "Updating KMLs for SCIP"
./grd2kml_2010_updated.sh

#Use this command when running for dates before 2010
#./grd2kml_before2010_updated.sh

cd ..
# finally, delete expanded time series and median time series files
rm -r $expandedTarFolder

