#!/bin/bash
#
# Run_all: Run all of the tests in this directory.
#
# Notes: Uses the test-list file specified on the command line
#		 to determine which tests to run.  (Default is set by
#		 the global variable TestList.)
#
#		 Comments begin with '#'.
#		 Test results are logged to results using tee.
#
#      -*- OpenSAF  -*-
#
# (C) Copyright 2008 The OpenSAF Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. This file and program are licensed
# under the GNU Lesser General Public License Version 2.1, February 1999.
# The complete license can be accessed from the following location:
# http://opensource.org/licenses/lgpl-license.php
# See the Copying file included with the OpenSAF distribution for full
# licensing terms.
#
# Author(s):
#           Hewlett-Packard Company
#
################################################################################

#*******************************************************************************
#                             Common Environment
#*******************************************************************************
shopt -s extglob        # POSIX regular expression matches
#*******************************************************************************
#                                  Libraries
#*******************************************************************************
 # Figure out where the libraries are located and source them
declare MyPath=$(which ${0##*/} | sed -e "s:/[^/]*$::")
[[ -z $LIB_PATH ]] && export LIB_PATH=${MyPath}/../lib
if [[ -s $LIB_PATH/libTestUtils ]]
then
   . $LIB_PATH/libTestUtils
else
   echo -e "\n**>ERROR: Couldn't find libTestUtils"
   exit 1
fi

#*******************************************************************************
#                          Global and Default Variables
#*******************************************************************************
export TestList="test.list"
 # Log of tests results
export TestLog=../results/hisv.$(hostname | sed -e "s/\..*//g").log.$(date +%m%d%y_%H%M%S)
[[ ! -d ../results ]] && mkdir ../results
 # Set VERBOSE and DRYRUN from the environment
export VERBOSE=${VERBOSE:-0}
export DRYRUN=${DRYRUN:-0}
export DEBUG=${DEBUG:-0}
export NO_RESET=1		# For cleanup routine to remove SKIP_TEST marker
export NO_COMPILE=0		# Flag to compile test code

#********************************************************************************
#                              Local Subroutines
#********************************************************************************

#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#  fParseUserOpts: Parse the user's command line
#  Input: $*, the user's command line
#  Output: Sets global variables
#  Return: void
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function fParseUserOpts
{
   # Allow the user to input args with or without an '='
	set -- $(echo $* | sed -e "s/=/ /g")

	while (( $# ))
	do
		local opt=$1
		shift
		case $opt in
			-\? | -h*(elp) )
				echo -e "\nUsage: $MyName [-f test_list_file] [-nocompile ] [-preview] [-v] [-debug]"
				echo -e "Where:"
				echo -e "\t-t\t    Specify the file with the list of tests to run."
				echo -e "\t\t    (default: $TestList)"
				echo -e "\t-nocompile   Skip test code compilation."
				echo -e "\t-preview    Don't run the tests, just print what would have been run."
				echo -e "\t-v\t    Verbose mode -- print out status reports"
				echo -e "\t-debug\t    set xtrace to debug"
				echo
				exit 0
				;;

			-debug | -x )
				# To debug.
				set -o xtrace
				export DEBUG=1
				;;

			-dryrun | -preview )
				DRYRUN=1
				;;

			-f | -l | -list | -cfg | -conf )
				if [[ -f $1 ]] 
				then
					TestList=$1
					shift
				else
					fErrorExit 1 "User specified '$opt' to set test-list file, but file doesn't exist"
				fi
				;;

			-log | -l )
				if [[ $1 = */* ]]
				then
					TestLog=${1}.log.$(eval $TS)
				else
					TestLog=../results/${1}.log.$(eval $TS)
				fi
				shift
				;;

			-no_compile | -no | -skip )
				NO_COMPILE=1
				(( VERBOSE )) && echo -e "\tNot compiling test code"
				;;

			-v | -verbose )
				VERBOSE=1
				;;

			
		esac
	done
}	# End fParseUserOpts

#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#  fCleanup: Clean up after the tests have run
#  Input: None
#  Output: Removes SKIP_TEST to start clean
#  Return: void
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function fCleanup
{
   (( ! $NO_RESET )) &&  rm -f SKIP_TEST
}

#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#  fRunCommand: Print and run a command
#  Input: command
#  Return: Return value of the command
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function fRunCommand
{
	local cmd="$*"
    local status=0
	(( VERBOSE || DRYRUN )) && echo "$cmd" | tee -a $TestLog
	if (( ! DRYRUN ))
	then
		$cmd 2>&1 | tee -a $TestLog
        status=${PIPESTATUS[0]}
	else
		status=0		
	fi
    return $status
}

#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#  fCompileTests: Compile the test code
#  Input: None
#  Return: Exits if build fails
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function fCompileTests
{
    (( $VERBOSE )) && echo "Compiling test code"
	cd ../
    if ! fRunCommand autoreconf -vi
    then
       NO_RESET=0
       fErrorExit $SKIPPED "autoreconf failed! Exiting"
    fi
    if ! fRunCommand configure
	then
       NO_RESET=0
       fErrorExit $SKIPPED "configure failed! Exiting"
	fi
    if ! fRunCommand make
	then
       NO_RESET=0
       fErrorExit $SKIPPED "failed to compile test code! Exiting"
	fi
	cd -
}

################################################################################
#                                     MAIN
################################################################################

# Cleanup after test run
trap 'fCleanup' EXIT ERR

# Parse the command line
fParseUserOpts $*

# Check user input
[[ ! -f $TestList ]] && fErrorExit 1 "No test-list file specified!"

# Compile the tests
[[ ! -f $TestLog ]] && touch $TestLog
(( ! NO_COMPILE )) && fCompileTests

# Print out system configuration
fShowConfig | tee $TestLog
export CONFIG_SHOWN=1

# Now run the tests
declare test
declare opts

sed -e "s/#.*//" -e "/^[ \t]*$/d" $TestList | \
while read test opts
do
	echo -e "\n============================================================" | tee -a $TestLog
	echo $test | tr [:lower:] [:upper:] | tee -a $TestLog
	echo -e "============================================================" | tee -a $TestLog
	fRunCommand $test $opts
done

# vim: tabstop=4
# -*- tab-width:4 -*-
