#!/bin/sh

# Script for replace obsoleted testrb from ruby-test-unit
# Use rake for testing and support Minitest::Test test units
# (c) 2016 Andrey Cherepanov <cas@altlinux.org>

# Get libs and test files
libs=""
files=""

. shell-getopt

function Usage {
	echo "Usage: testrb [-Ipath1:path2...] tests..."
	exit 0
}

# Process command line arguments by shell-getopt
while getoptex "v: I:" "$@"; do
    case "$OPTOPT" in 
        I) libs="$libs $(echo "$OPTARG"|tr ':' ' ')";;
    esac
done
shift $(($OPTIND-1))
set -- $@ ${OPTUKN-}
for p in "$@"; do
    # Check if test exists
    if [ ! -e "$p" ]; then
    	echo "Ignore missing path '$p'"
    	continue
    fi
    # Check if test is dir
    if [ -d "$p" ]; then
    	p="$(ls -1 "$p/test*.rb"|tr '\n' ' ')"
    fi
    files="$files $p"
done

# Remove trailing whitespaces and default lib directory
libs="$(echo "$libs"|tr ' ' '\n'|grep -v '^lib$'|tr '\n' ' '|sed 's/^ *//;s/ *$//')"
files="$(echo "$files"|sed 's/^ *//;s/ *$//')"

# Check if test list is empty
if [ -z "$files" ]; then
	Usage
fi

# Create Rakefile
rake_file="$(mktemp -u -t Rakefile.XXXXXX)"
cat > "$rake_file" << END.
require 'rake/testtask'
Rake::TestTask.new do |task|
  task.libs << %w($libs test)
  task.test_files = FileList[%w($files)]
  task.verbose = true
end
END.

# Perform testing
rake -f "$rake_file" test
ret="$?"

# Remove temp file
rm -f "$rake_file"

exit $ret
