#!/bin/sh
#################################################################################
##                                                                             ##
##                        l  p  j  r  u  n                                     ##
##                                                                             ##
##    sh script to run parallel LPJmL program interactively. Script calls      ##
##    mpirun defined in MPICH. Works on Apple MacOS X                          ##
##                                                                             ##
##    Usage: lpjrun ntasks [LPJargs...]                                        ##
##                                                                             ##
## (C) Potsdam Institute for Climate Impact Research (PIK), see COPYRIGHT file ##
## authors, and contributors see AUTHORS file                                  ##
## This file is part of LPJmL and licensed under GNU AGPL Version 3            ##
## or later. See LICENSE file or go to http://www.gnu.org/licenses/            ##
## Contact: https://github.com/PIK-LPJmL/LPJmL                                 ##
##                                                                             ##
#################################################################################

hosts=""

USAGE="Usage $0 -hostfile hosts num [lpjargs...]"

while(( "$#" )); do
  case "$1" in
  -hostfile)
    if [ $# -lt 2 ]
    then
      echo >&2 Error: hostfile missing
      echo >&2 $USAGE
      exit 1
    fi
    shift 1
    hosts=$1
    shift 1
    ;;
  -*)
     echo >&2 Invalid option $1
     echo >&2 $USAGE
     exit 1
     ;;
   *)
     break
     ;;
  esac
done
if [ $# -lt 1 ]
then
  echo >&2 Error: Number of tasks missing
  echo >&2 $USAGE
  exit 1
fi
if [ "$LPJROOT" = "" ]
then
  echo >&2 Error: environment variable LPJROOT is not set
  echo >&2 "Set by export LPJROOT=<path to lpjml directory>"
  exit 1
fi
ntasks=$1
shift 1
args=$*
if [ "$hosts" != "" ]
then
  mpirun -np $ntasks -hostfile $hosts $LPJROOT/bin/lpjml $args
else
  mpirun -np $ntasks $LPJROOT/bin/lpjml $args
fi
rc=$?
exit $rc
