#!/bin/bash

function usage() {
  echo "Usage: $0 appCMD "
  echo "-- Launch the appCMD with 'vglrun' in the job scheduler GPU environment \$GPU_ALLOCATION."
  echo "-- If 'vglrun' or \$GPU_ALLOCATION does not exist, just launch the appCMD directly."
  echo "------"
  exit 0
}

#while [ $# != '0' ]; do
#  case $1 in
#  *=*) optarg=`expr "X$1" : '[^=]*=\(.*\)'` ;;
#  *)  optarg=no ;;
#  esac
  case $1 in
  -h)
        usage ;;
  --help)
        usage ;;
  *)
        ;;
  esac
#  shift
#done

APP_CMD_OPT="$*"
#echo ${APP_CMD_OPT}

###Must be invoked within the job/resource scheduler environment.
if [ x"${CB_JOBID}" == x"" ]; then
  echo "Error! $0 must be invoked within the job/resource scheduler."
  exit 151
fi

###Get the command path of 'vglrun'
VGL_RUN_CMD=""
which vglrun >/dev/null 2>&1 
if [ x"$?" == x"0" ]; then
  VGL_RUN_CMD=`which vglrun`
fi

###Lauch the appCMD with/without GPU
if [ x"${GPU_ALLOCATION}" != x"" ] && [ x"${VGL_RUN_CMD}" != x"" ]; then
  #Get the last section of $GPU_ALLOCATION
  GPU_ID=`echo ${GPU_ALLOCATION} | awk -F ":|," '{print $NF}'`
  eval ${VGL_RUN_CMD} -d :0.${GPU_ID} ${APP_CMD_OPT}
else
  eval ${APP_CMD_OPT}
fi
