#!/bin/sh
# vim: set filetype=sh :
#        file: run_tests
#   copyright: Bernd Schumacher <bernd.schumacher@hpe.com> (2007-2018)
#     license: GNU General Public License, version 3
# description: run shellia internal tests

VERBOSE=""
while [ $# -gt 0 ]; do
  if [ "$1" = "-v" ]; then
    VERBOSE="$1"
    shift
  else
    echo "ERROR run_tests: unknown option <$1>" >&2
    exit 1
  fi
done

# test_with_sh <testfile> <sh>
test_with_sh()
{
  local out
  out="$("./$1" -s "$2" 2>&1)"
  if [ "$(echo "$out" | grep -e "^ERROR")" ]; then
    [ "$VERBOSE" ] && echo "$out" || echo "ERROR \"./$1\" -s \"$2\""
    err=$((err +1))
  else
    [ "$VERBOSE" ] && echo "$out" || echo "OK \"./$1\" -s \"$2\""
  fi
}

rm -f timelist

err=0
for testfile in test\.*; do
  if [ "$testfile" = "test.prefix" ]; then
    # dash can not list functions, but bash can
    for sh in bash; do
      test_with_sh "$testfile" "$sh"
    done
  elif [ "$testfile" = "test.only_interactive" ]; then
    # posh does not respect exit (independly from shellia)
    for sh in bash dash "busybox sh" mksh; do
      test_with_sh "$testfile" "$sh"
    done
  elif [ "$testfile" = "test.ia_mktemp" ]; then
    # posh Bug#910275
    # mksh Bug#910276
    for sh in bash dash "busybox sh"; do
      test_with_sh "$testfile" "$sh"
    done
  else
    #for sh in bash dash "busybox sh" mksh posh yash zsh sash; do
    for sh in bash dash "busybox sh" mksh posh; do
      test_with_sh "$testfile" "$sh"
    done
  fi
done

s="$(
( echo "( "
  cat timelist | sed "s/^real=\([0-9]\+\):.*/\1+/"
  echo "0 ) * 3600"

  echo "+"

  echo "( "
  cat timelist | sed "s/^real=[0-9]\+:\([0-9]\+\)\..*/\1+/"
  echo "0 ) * 60"

  echo "+"

  cat timelist | sed "s/^real=[0-9]\+:[0-9]\+\.\([0-9]\+\).*/\1+/"
  echo 0
) | xargs | bc)"
#echo "s=$s"
h=$((s/3600))
s=$((s-h*3600))
m=$((s/60))
s=$((s-m*60))
date "+%Y/%m/%d-%H:%M $h:$m.$s err=$err times=$(cat timelist | wc -l)" >> timelist.all

echo "$err Errors"
exit $err
