#!/bin/bash

# **************************** LICENSE START ***********************************
#
# Copyright 2012 ECMWF and INPE. This software is distributed under the terms
# of the Apache License version 2.0. In applying this license, ECMWF does not
# waive the privileges and immunities granted to it by virtue of its status as
# an Intergovernmental Organization or submit itself to any jurisdiction.
#
# ***************************** LICENSE END ************************************


# ---------------------------------------------------------
# Script to run FLEXPART from within Metview
# ---------------------------------------------------------

set -x

print_err()
{
	echo ${text_ERR}  $* >> "${f_LOG}"
} 

text_ERR="Script `basename $0` FAILED> "

#Get args

if [ $# -ne 3 ] ; then
    echo "Invalid number of arguments specified! (" $# " instead of 3)"
    exit 1
fi

d_WORK=$1
f_LOG=$2
f_EXE=$3

if [ "$f_EXE" = "_UNDEF_" ] ; then
	exe_FLEXPART=${MV_FLEXPART_EXE}
else
	exe_FLEXPART=${f_EXE}
fi

#-------------------------------
# Go to working directory 
#-------------------------------

if [ ! -d "$d_WORK" ] ; then   
   print_err "No working directory found: " $d_WORK
   exit 1
fi

cd $d_WORK

#-------------------------------
# Checks
#-------------------------------

if [ x"$exe_FLEXPART" = "x" ] ; then   
   print_err "No FLEXPART executable is defined. Please define it via env variable MV_FLEXPART_EXE."
   exit 1
fi

if [ ! -f "$exe_FLEXPART" ] ; then   
   print_err "No FLEXPART executable found: " $exe_FLEXPART
   exit 1
fi

if [ ! -x "$exe_FLEXPART" ] ; then   
   print_err "FLEXPART executable cannot be run! Permission is missing. " $exe_FLEXPART
   exit 1
fi

#species
d_PAR="/var/tmp/$USER/work/flexpart/FLEXPART_902/options"

cp ${d_PAR}/IGBP_int1.dat .
cp ${d_PAR}/OH_7lev_agl.dat .
cp ${d_PAR}/surfdata.t .
cp ${d_PAR}/surfdepo.t .
ln -sf ${d_PAR}/SPECIES SPECIES

#-------------------------------
#Run flextra
#-------------------------------

$exe_FLEXPART>${f_LOG} 2>&1 
outCode=$?


#-----------------------------------
#  Check log
#-----------------------------------

if [ -f ${f_LOG} ] ; then
  if [ `grep -c -i WARNING $f_LOG` -ne 0 ] ; then
	outCode=255 
  elif [ `grep -c -i ERROR $f_LOG` -ne 0 ] ; then
	outCode=1
  elif [ $outCode -ne 0 ] ; then
	outCode=$outCode
  fi  
fi

	
exit $outCode
