#!/bin/sh
#$ -o /exports/csce/eddie/geos/groups/LURG/models/PLUM/output/qlogs
#$ -e /exports/csce/eddie/geos/groups/LURG/models/PLUM/output/qlogs
#$ -l h_vmem=8G 
#$ -R y

while getopts ":s:b:p:r:" opt; do
  case ${opt} in
    b )
      build=${OPTARG}
      ;;
    s )
      scenario=${OPTARG}
      ;;
    p )
      prune=${OPTARG}
      ;;
    r )
      r_summary=${OPTARG}
      ;;
  esac
done

echo SCENARIO $scenario
if [ -z ${scenario+x} ];
then
   echo "scenario is unset"
   exit -1
fi

build="${build:-.}"
echo BUILD $build

if [[ -e /exports/csce/eddie/geos/groups/LURG/models ]]; then
  echo Edinburgh
  . /etc/profile.d/modules.sh
  module load java
  GAMSPATH=/exports/csce/eddie/geos/groups/LURG/models/gams/gams24.7_linux_x64_64_sfx
  PLUMPATH=/exports/csce/eddie/geos/groups/LURG/models/PLUM
fi

if [[ $HNAME =~ "kea" ]]; then
  module load app/gams/24.3.1
  module load app/jdk/1.8.0 
  module list
  GAMSPATH=/app/gams-24.3.1/gams24.3_linux_x64_64_sfx
  PLUMPATH=$PWD
fi

if [[ $HNAME =~ "fh1" ]]; then
  module load devel/jdk/1.8.0_102
  module list
  #kind of hardwired to my GAMS installation
  GAMSPATH=~ku7787/software/gams/gams24.6_linux_x64_64_sfx
  PLUMPATH=$PROJECT/PLUM
fi

PATH=$PATH:$GAMSPATH
export PATH

classesdir=$PLUMPATH/$build/classes
if [ ! -d "$classesdir" ]; then
    echo $classesdir does not exist. Stopping!
    exit -1
fi

buildver="$(cat $classesdir/buildver)"
echo buildversion: $buildver

scenariodir=$PLUMPATH/output/$scenario
if [ ! -d "$scenariodir" ]; then
    echo Directory for scenario $scenariodir does not exist. Stopping!
    exit -1
fi

cd $scenariodir

echo "starting"
runcmd="java -Xmx1G -XX:+PrintGC -classpath $GAMSPATH/apifiles/Java/api/GAMSJavaAPI.jar:$classesdir -DBUILDVER=$buildver -DCONFIG_FILE=$scenariodir/config.properties ac.ed.lurg.ModelMain"
echo $runcmd
$runcmd
echo "finished"

if [[ $r_summary =~ "y" ]]; then
   echo "Running R summarising script"
   module load R
   R < $PLUMPATH/plumv2/scripts/summariseLandUseOneSim.R  --no-save --args $scenario
else
   echo "Not running R summarising script"
fi

if [[ $prune =~ "y" ]]; then
   echo "Pruning outputs, to save disk space"
   cd $scenariodir
   tar -zcvf forLpjg.tar.gz 2*
   $PLUMPATH/plumv2/scripts/pruneOutputs.sh $scenariodir
else
   echo "Not pruning outputs"
fi

