#! /bin/bash

set -e

BASEDIR="$(dirname "$0")"

function die {
    echo "$@" 1>&2
    exit 1
}

function usage {
    die "usage: $(basename "$0") [DOMAIN_FILE] PROBLEM_FILE SEARCH_OPTION ..."
}

# Paths to planner components
TRANSLATE="$BASEDIR/translate/translate.py"
PREPROCESS="$BASEDIR/preprocess/preprocess"
SEARCH="$BASEDIR/search/downward"

# Settings
INV_TIME_LIMIT="300"

# Check for citation request
if [ "--citation" = "$1" ]; then
  echo "
@inproceedings{muise12icapsfond,
  author = {Christian Muise and Sheila A McIlraith and J Christopher Beck},
  title = {Improved Non-deterministic Planning by Exploiting State Relevance},
  booktitle = {The 22nd International Conference on Automated Planning and Scheduling (ICAPS)},
  year = {2012},
  subdiscipline = {Artificial Intelligence},
  type = {Conference Proceedings}
}

@inproceedings{muise-aaai-14,
  title={Computing Contingent Plans via Fully Observable Non-Deterministic Planning},
  author={Muise, Christian and Belle, Vaishak and McIlraith, Sheila A.},
  booktitle={The 28th AAAI Conference on Artificial Intelligence},
  year={2014},
  url={http://www.haz.ca/papers/muise-aaai-14.pdf}
}

@inproceedings{muise-icaps-14,
  title={Non-Deterministic Planning With Conditional Effects},
  author={Muise, Christian and McIlraith, Sheila A. and Belle, Vaishak},
  booktitle={The 24th International Conference on Automated Planning and Scheduling},
  year={2014},
  url={http://www.haz.ca/papers/muise-icaps-14.pdf}
}
"
  exit 1
fi

# Need to explicitly ask for GNU time (from MacPorts) on Mac OS X.
if [[ "$(uname)" == "Darwin" ]]; then
    TIME="gtime"
    if ! which $TIME >/dev/null; then
        die "$TIME must be installed on Mac OSX (from MacPorts, perhaps) for this to work"
    fi
else
    TIME="command time"
fi

TIME="$TIME --output=elapsed.time --format=%S\n%U\n"

if [[ "$#" -lt 2 ]]; then
    usage
fi

IPC="ipc"
if [[ "$1" == "debug" ]]; then
    IPC="debug $IPC"
    shift
fi

echo "1. Running translator"
if [[ -e "$2" ]]; then
    echo "Second argument is a file name: use two translator arguments."
    # $TIME "$TRANSLATE" "$INV_TIME_LIMIT" "$1" "$2"
    "$TRANSLATE" "$INV_TIME_LIMIT" "$1" "$2"
    shift 2
else
    echo "Second argument is not a file name: auto-detect domain file."
    # $TIME "$TRANSLATE" "$INV_TIME_LIMIT" "$1"
    "$TRANSLATE" "$INV_TIME_LIMIT" "$1"
    shift
fi
echo

echo "2. Running preprocessor"
#$TIME --append "$PREPROCESS" < output.sas
"$PREPROCESS" < output.sas
echo

echo "3. Running search"
echo "$SEARCH" "$IPC" policy-repair < output "$@"
"$SEARCH" $IPC policy-repair < output "$@"
echo


