#!/usr/bin/env bash
# Usage:
#   ./x up
#       Upload the compiled code and the run file into a bundle called `stuff`
#   ./x {walk|run|jog} [-n] [-- additional_dependencies --] run_arguments
#       Call cl run on the ./run script. The run name is automatically generated.
#       Use -n to print the command and exit.

operation=$1
shift
queue=
if [ "$operation" == "up" ]; then
  mkdir xxx || exit 1
  ln -s ../src xxx/
  ln -s ../libsempre xxx/
  ln -s ../module-classes.txt xxx/
  ln -s ../tables/grammars xxx/
  ln -s ../run xxx/
  { hostname; readlink -f .; date; git log -1; git status; } > xxx/git-hash
  cl upload -L -n stuff xxx
  rm -rf xxx
  exit 0
elif [ "$operation" == "walk" ]; then
  queue="--request-memory 11g --request-cpus 2 --request-queue nlp"
elif [ "$operation" == "run" ]; then
  queue="--request-memory 11g --request-cpus 2 --request-queue john"
elif [ "$operation" == "jog" ]; then
  queue="--request-memory 11g --request-cpus 2 --request-queue jag"
else
  echo "Available operation: up walk run jog"
  exit 1
fi

dryrun=
if [ "$1" == "-n" ]; then
  shift
  dryrun=1;
fi

dependencies=":fig :lib libsempre:stuff/libsempre module-classes.txt:stuff/module-classes.txt run:stuff/run grammars:stuff/grammars :WikiTableQuestions"
if [ "$1" == "--" ]; then
  shift 
  while [ "$1" != "--" ]; do
    dependencies="$dependencies $1"
    shift
  done
  shift
fi

prefix=`hostname`
if [[ "$prefix" == j* ]]; then
  prefix="nlp"
elif [ "$prefix" != "nazrin" -a "$prefix" != "fandango" ]; then
  prefix="what"
fi
name=$(YAY=$(cat .cnt.info || echo 0) && echo $(($YAY + 1)) > .cnt.info && echo -n $prefix-$YAY.cl)
cl_run_args="cl run $queue -n $name $dependencies"
cl_run_command="LC_ALL=C.UTF-8 ./run @cldir=1 $*"
echo "$cl_run_args \"$cl_run_command\""
[ $dryrun ] || $cl_run_args "$cl_run_command"
