#!/usr/bin/env bash

ERT_RUNNER="/usr/share/emacs/site-lisp/ert-runner/ert-runner.el"

function inside_emacs_24 {
  if [[ -n $INSIDE_EMACS ]] &&
         ## Emacs-24 sets INSIDE_EMACS to t with M-x compile, and to a string
         ## starting with version numbers in shell
         ([[ $INSIDE_EMACS == t ]] || [[ $INSIDE_EMACS == 24* ]]); then
      return 0
  fi
  return 1
}

function has_option {
  for opt in "${@:2}"; do
    [[ "$opt" == "$1" ]] && return 0;
  done
  return 1
}

if inside_emacs_24; then
  ERT_RUNNER_EMACS="emacs"
else
  ERT_RUNNER_EMACS="${EMACS:-emacs}"
fi

export ERT_RUNNER_ARGS="${@}"

if has_option "--win" $@ || has_option "--no-win" $@ ; then
  export ERT_RUNNER_OUTFILE=$(mktemp /tmp/ert-runner.XXX)

  if has_option "--win" $@; then
    "$ERT_RUNNER_EMACS" --load "$ERT_RUNNER" -q
  else
    "$ERT_RUNNER_EMACS" -nw --load "$ERT_RUNNER" -q
  fi

  STATUS=$?

  cat $ERT_RUNNER_OUTFILE
  rm -f $ERT_RUNNER_OUTFILE

  exit $STATUS
else
  "$ERT_RUNNER_EMACS" --script "$ERT_RUNNER" -q
fi
