#!/usr/bin/env bash

set -eu

version="0.8.4"

current_dir="$(pwd)"

bin_path="$0"
while [[ -L "$bin_path" ]]; do
  cd "$(dirname $bin_path)"
  bin_path="$(readlink ${bin_path##*/})"
done

bin_dir="$(cd "$(dirname ${bin_path})" && pwd)"
lib_dir="$(cd "${bin_dir}/../lib" && pwd)"
. "${lib_dir}/shove.bashrc"

cd "$current_dir"

[[ ${SHOVE_DEBUG:-} ]] && set -x

mkdir -p $SHOVE_WORKDIR

targets=()

# ============================================================
# Parse Arguments

for opt in "$@"; do
  case "${1:-}" in
    "-s" | "--shell" )
      if [[ -z $2 || "$2" =~ ^-+ ]]; then
        help
      else
        SHOVE_SHELL=$2
        shift 2
      fi
      ;;
    "-r" | "--recurse" )
      if [[ -z $2 || "$2" =~ ^-+ ]]; then
        help
      else
        targets+=($(find $2 -type f -name '*.t'))
        shift 2
      fi
      ;;
    "-v" | "--verbose" )
      SHOVE_VERBOSE=1
      shift
      ;;
    "-h" | "--help" )
      help
      ;;
    "-V" | "--version" )
      echo $version
      exit 0
      ;;
    * )
      if [[ ${1:-} ]]; then
        targets+=($1)
        shift
      fi
      ;;
  esac
done

export SHOVE_SHELL=${SHOVE_SHELL:-$SHELL}
SHOVE_SHELL_CMD=$SHOVE_SHELL

if [ $SHOVE_DEBUG ]; then
  SHOVE_SHELL_CMD="$SHOVE_SHELL -x"
fi

# ============================================================
# Main Entry

purge_tmp_files

cat <<EOS >&1
Run tests by $SHOVE_SHELL_CMD
-------------------------
EOS

t_cnt=0
for tgt in ${targets[@]}; do
  t_cnt=$((t_cnt + 1))
  test_file $tgt
done

final_report

exit $?

: <<'__EOF__'

=encoding utf8

=head1 NAME

B<shove> - A test tool for shell scripts

=head1 SYNOPSYS

    shove TARGETS [OPTIONS]
    shove t/foo.t
    shove t/bar.t t/bar.t -s /bin/sh -v
    shove -r t/ -v

Help:

    shove -h|--help

Show version:

    shove -V|--version

=head1 DESCRIPTION

This script runs target test scripts.

=head1 AUTHORS

IKEDA Kiyoshi E<lt>progrhyme@gmail.comE<gt>

=head1 LICENSE

The MIT License (MIT)

Copyright (c) 2016-2020 IKEDA Kiyoshi

=cut

__EOF__

