#!/bin/bash -e
# Copyright 2009-2014 Apple Inc. All rights reserved.

BINDIR="%%BINDIR%%"
BINDIR="${BINDIR/%%*%%/.}"

# If not already set by bsdtesttool
if [ -z "$BSDTESTS_TMPDIR" ]; then
	BSDTESTS_TMPDIR="$(mktemp -d -t bsdtests)/"
	export BSDTESTS_TMPDIR
	echo "Using temp dir $BSDTESTS_TMPDIR"
fi

function dotest {
	T="\"$BINDIR\"/bsdtestharness ./$1"
	LOG="${BSDTESTS_TMPDIR}$1${2:+.$2}"
	SEP="\n**** %-40s ****\n"
	
	if [ -n "$BSDTESTS_STRESS" ]; then
		x=0
		while (( x < BSDTESTS_STRESS )); do
			printf "$SEP" "$1 $2 stress $x"
			eval $ENVIRON $T 2>&1 | tee -a "$LOG.$x.testlog"
			let x+=1
		done
	else
	printf "$SEP" "$1 $2"
	eval $ENVIRON $T 2>&1 | tee -a "$LOG.testlog"
	if [ -z "$BSDTESTS_PREBUILD" ]; then
		printf "$SEP" "$1 debug $2"
		eval $ENVIRON DYLD_IMAGE_SUFFIX=_debug $T 2>&1 | tee -a "$LOG.debuglog"
	fi
	fi
}

function runtest {
	echo; echo "   Libc test: $1 ..."
	ENVIRON="LIBDISPATCH_LOG=NO"
	dotest "$1"
	if [ -n "$(lipo -info /usr/lib/libSystem.dylib 2>&- | grep i386)" \
			-a "$(sysctl -n hw.optional.x86_64 2>&-)" = "1" ]; then
		ENVIRON="$ENVIRON BSDTEST_ARCH=i386"
		dotest "$1" "i386"
	fi
}

cd $(dirname $0)
rm -f "${BSDTESTS_TMPDIR}"*.{test,debug,gctest,gcdebug,leaks}log

if [ "$1" == "--nosummary" ]; then
	NOSUMMARY=1; shift
fi

if [ "$#" -gt 0 ]; then
	if [ "$1" == "--help" ]; then
		echo "Usage: $0 [--nosummary] [<test>|<test>|...]";
		echo "		--nosummary		run all tests but do not summarize results at the end"
		exit 0;
	fi
	for T in "$@"; do runtest $T; done
else
	for T in $(cat test_list.txt); do runtest $T; done
fi

if [ -z "$NOSUMMARY" -a -x "$BINDIR"/bsdtestsummarize ]; then
	shopt -s nullglob
	cat "${BSDTESTS_TMPDIR}"*.{test,debug,gctest,gcdebug}log | "$BINDIR"/bsdtestsummarize
fi
	
