#!/usr/bin/env bash

##########################################
# country should be written lowercase, or how appears in coords.conf
# date currently does not function and will return always today's date (or most recent available)
# only monarch accepts all variables, the rest get od550_dust and sconc_dust
# anim should only be called with true here, as the pngs are automatically deleted
# ./bin/gen_country_loop.sh monarch true sconc_dust 20220808 spain

# for development change repodir and currdir
# generate daily maps for specified couuntry
# usage: script.sh [model] [anim] [variable] [date] [country]

if [ "$1" != "" ]; then
    model="$1"
else
    model="all"
fi

if [ "$2" != "" ]; then
    anim="$2"
else
    anim="true"
fi

if [ "$3" != "" ]; then
    curvar="$3"
else
    curvar="all"
fi

if [ "$4" != "" ]; then
    curdate="$4"
else
    curdate=`date '+%y%m%d' -d '-1day'`
fi

if [ "$5" != "" ]; then
    country="$5"
else
    country="default"
fi

curyear=`date '+%Y' -d ${curdate}`
curmon=`date '+%m' -d ${curdate}`
repodir='/data/daily_dashboard/comparison/'

runProcess () {
    tmpdir=${HOME}/tmp/${var}/${country}
    mkdir -p $tmpdir
    rm -rf $tmpdir/*
    # SET REPO AND FILENAME FOR NON-COUNTRY SELECTIONS 
    currepo=${repodir}/${model}/${variable}/${curyear}/${curmon}
    filename=${curdate}_${model}
    # SET FOLDER STRUCTURE AND FILENAME FOR SPECIFIC COUNTRIES
    if [ "$country" != "default" ] && [ "$country" != "monarch_fit" ]; then 
	tmpdir=${HOME}/tmp/${var}/${country}
	mkdir -p $tmpdir
	rm -rf $tmpdir/*
	currepo=${repodir}/${model}/${variable}/${curyear}/${curmon}/${country}
	filename=${curdate}_${model}_${country}
    fi
    node js/create_model_loop_zoom_fit.js $anim $model $curdate $variable $country
    wait
    sleep 1
    convert -loop 0 -delay 25 ${tmpdir}/${filename}_??.png ${tmpdir}/${filename}_loop.gif
    mkdir -p $currepo
    wait
    mv ${tmpdir}/${filename}_* $currepo
    rm $currepo/${filename}_??.png
}

for var in od550_dust sconc_dust dust_depd dust_depw dust_load dust_ext_sfc
do
	variable=$var
	echo "************ $model $anim $curvar $variable $curdate $country****************"
	if [ "$curvar" != "$variable" ] && [ "$curvar" != "all" ]; then
		continue
	fi
	# IF VARIABLE ISN'T AOD OR CONCENTRATION, FORCE MONARCH
	if [ "$variable" != "od550_dust" ] && [ "$variable" != "sconc_dust" ]; then
	    model="monarch"
	    runProcess 
	# IF MODEL INPUT IS ALL, RUN THROUGH ALL MODELS
	elif [ "$model" == "all" ]; then
	    selectedCountry=$country
	    for model in `cat ./conf/models.json | grep '": {' | sed 's/^.*"\(.*\)".*$/\1/g'`
		do
		    if [ "$model" == "monarch" ] && [ "$country" == "default" ]; then
			country="monarch_fit"
		    else
			country=$selectedCountry
		    fi
		    runProcess
		done
	# PRODUCE GIF FOR DECLARED MODEL AND VARIABLE
	else
	    runProcess
	fi
	wait
	sleep 1
done
