#!/usr/bin/env bash
#
# Iterates over a list of NDJSON files and pipes it into a formatter command. The STDOUT
# and STDERR is written to a file whose name is derived from the base name of 
# the input file.
#
# This script is used to verify that a message consumer (formatter) is able to
# process messages generated by a Cucumber implementation.
#
# Examples: 
#  ./scripts/run-formatter -e .html -o /tmp -c "./scripts/cucumber-html-formatter" ../../compatibility-kit/javascript/features/**/*.ndjson
set -uf
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

while getopts "o:c:e:" option; do
  case "${option}" in
  o)
    outdir=${OPTARG}
    ;;
  c)
    command=${OPTARG}
    ;;
  e)
    extension=${OPTARG}
    ;;
  *)
    echo "Error :-("
    exit 1;
    ;;
  esac
done
shift $((OPTIND - 1))
if [ -z "${outdir}" ]; then
  echo "missing -o"
  exit 1;
fi
if [ -z "${command}" ]; then
  echo "missing -c"
  exit 1;
fi
if [ -z "${extension}" ]; then
  echo "missing -e"
  exit 1;
fi

exitstatus=0
for ndjson in $*; do
  name="${outdir}/$(basename "${ndjson}")"
  stdout="${name}${extension}"
  stderr="${name}${extension}.err.txt"
  output=$(${command} < "${ndjson}" 2> "${stderr}" > "${stdout}")

  if [ $? = 0 ]; then
    echo -e "${GREEN}✔${NC} ${ndjson}"
  else
    echo -e "${RED}✘${NC} ${ndjson}"
    exitstatus=1
  fi
done

exit ${exitstatus}
