#!/usr/bin/env bash

# ecukes --- Cucumber for Emacs

# Copyright (C) 2010-2013 Johan Andersson
# Copyright (C) 2012 Joel McCracken
# Copyright (C) 2012 Dave Paroulek
# Copyright (C) 2013 Kyle Hargraves
# Copyright (C) 2013 Takafumi Arakaki

# Author: Johan Andersson <johan.rejeep@gmail.com>
# Maintainer: Johan Andersson <johan.rejeep@gmail.com>
# Version: 0.6.15
# Keywords: testing, cucumber
# URL: http://ecukes.info

# This file is NOT part of GNU Emacs.

# License:

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with GNU Emacs; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.

ECUKES_HOME=$(dirname "$(dirname "$BASH_SOURCE")")
ECUKES_CLI=$ECUKES_HOME/ecukes-cli.el

if [[ -n "$INSIDE_EMACS" ]]; then
  ECUKES_EMACS="emacs"
else
  ECUKES_EMACS="${EMACS:-emacs}"
fi

function has_option {
  for opt in "${@:2}"; do
    [[ "$opt" == "$1" ]] && return 0;
  done
  if [[ -e ".ecukes" ]] ; then
      for fileopt in $(cat ".ecukes") ; do
          [[ "$fileopt" == "$1" ]] && return 0;
      done
  fi
  return 1
}

export ECUKES_ARGS="${@}"

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

  if has_option "--win" $@; then
    "$ECUKES_EMACS" --load "$ECUKES_CLI" -Q
  else
    "$ECUKES_EMACS" -nw --load "$ECUKES_CLI" -Q
  fi

  STATUS=$?

  cat $ECUKES_OUTFILE
  rm -f $ECUKES_OUTFILE

  exit $STATUS
else
  "$ECUKES_EMACS" --script "$ECUKES_CLI" -Q
fi
