#! /bin/sh --posix
# Include --posix which looks to be necessary, on Linux anyway, to
# not read in the .bashrc file again where the PNFS_DIR and LOCAL_DIR
# variables are possibly set.

# $Id$

#Main script to run encp regression tests.
#
# Requires $ENSTORE_DIR/tools/encp_test_functions and
# $ENSTORE_DIR/tools/encp_create_tests to work.
# 
# Requires $LOCAL_DIR and $PNFS_DIR to be set.

#To add a new test:
# 1) Add the name to the end of the list_of_tests variable in encp_test_script.
# 2) Add a function at the end of the encp_test_functions file with that
#    name.  This function needs to run the test.  See existing tests for
#    examples.

#Define the list of tests.
list_of_encp_tests="single_read_test
                    single_read_write_test
                    dcache_read_write_test
                    dcache_shortcut_read_write_test
                    dcache_override_path_read_write_test
                    dcache_dirpath_read_write_test
                    dcache_dirpath_shortcut_read_write_test
                    enstore_conf_read_write_test
                    single_threaded_read_write_test
                    multiple_threaded_read_write_test
                    single_ecrc_read_write_test
                    single_relative_path_read_write_test
                    single_local_pnfs_path_read_test
                    single_no_brand_read_test
                    volume_read_test
                    single_fs_path_read_test
                    data_access_layer_read_write_test
                    multiple_copies_read_write_test
                    pnfs_agent_read_write_test
                    setuid_read_write_test
                    pipe_write_test
                    source_file_does_not_exist_write_test
                    library_does_not_exist_write_test
                    too_many_resubmits_write_test
                    skip_sfs_read_test
"

list_of_other_tests="single_assert_test
                     ensync_test
                     get_put_test
                     get_volume_test
                     enmv_test
"

##
## Start of functions.
##

print_help()
{
    echo "USAGE: `basename $0` [ options ] [<test_name1> [test_name2] ...]"
    echo "    -h               Print this help."
    echo "    -e <encp_path>   Specifiy the encp to use for the tests."
    echo "    -d               Increase the debugging output with each -d."
    echo "    -t               Truncate output log file after each test. (default)"
    echo "    -a               Keep appending output to log file after each test."
    echo "    -n <num>         Number of passes of test(s) to run. (default 1)"
    echo "    -s <num>         Simultaneous tests to run per pass. (default 1)"
    echo "    -c               Cleanup leftover files from previous tests."
    echo "    -q               Set debug level to 0."
    echo "    -l <dir>         The local directory to use; or use \$LOCAL_DIR."
    echo "    -p <dir>         The storage directory to use; or use \$PNFS_DIR."
    echo 
    echo "List of Encp Tests:"
    echo 
    for name in `echo "$list_of_encp_tests"`; do
        echo $name
    done
    echo
    echo "List of Other Tests:"
    echo
    for name in `echo "$list_of_other_tests"`; do
        echo $name
    done
}

is_integer_argument()
{
    [ `echo "$1" | sed 's/^[-+0-9][0-9]*//' | wc -c` -eq 1 ]
    if [ $? -ne 0 ]; then
        #We were not passed a number
        echo "Number expected, not $1." 1>&2
        exit 2
    elif [ $number -lt 0 ]; then
        echo "Negative numbers, like $1, are not allowed." 1>&2
        exit 2
    fi
}

run_tests()
{
    setup_log_file

    #Run the tests.
    for test_name in `echo "$list_of_encp_tests" "$list_of_other_tests"`; do
	if [ $(eval echo \$$test_name) = yes ]; then
            #If -t in effect, truncate the log file.  If it does not exist,
	    # create it.
	    truncate_encp_output  

	    #
	    #Execute the test.
	    #
	    eval $test_name
	fi
    done

    #Only used for successful tests here, but print the success message to
    # the user.  Error cases exit, which cause all_done to be called from
    # a trap.  Either way the successful or error exist status is still
    # collected by the collect_children function.
    all_done
}

# Run a pass worth of tests.  Saving forked child PIDs in $saved_pids.
run_test_pass()
{
   #Run the number of simultaneous tests requested at one time for each pass.
   j=1
   saved_pids=
   while [ $j -le $simultaneous ]; do
       j=$((j + 1))

       #Fork off a new shell to run this pass of the test.
       run_tests &
       saved_pids=`echo -e "${saved_pids}\n$!"`
   done
   collect_children  #Uses $saved_pids.
   return $?
}

# Get the exit status of the sub-shell processes saved in $saved_pids
# started by run_test_pass.
collect_children()
{
    exit_status=0

    for pid in `jobs -p`; do
        wait $pid
        rc=$?
        if [ $rc -ne 0 ]; then
            #There were no errors.
            exit_status=$rc
        fi
    done
    return $exit_status
}

##
## End of functions.
##

verbose="--verbose 9"

alias ls > /dev/null 2>&1
if [ $? -eq 0 ]; then
    unalias ls 2> /dev/null   #We want the default ls behavior.
fi

#These variables are possibily overridden with command line arguments.
encp_cmd=${encp_cmd:-`which encp`}
debug=${debug:-1}
truncate_output=${truncate_output:-yes}
number=${number:-1}
simultaneous=${simultaneous:-1}
cleanup=${cleanup:-no}

#Parse any command line arguments.
#
# encp_cmd and debug are used in encp_test_functions function transfer().
# 
while getopts dhe:atn:s:cql:p: option; do
    case "$option"
    in
        e) if [ -x "$OPTARG" ]; then
	       encp_cmd=`which $OPTARG`  #Use which to force absolute path.
           elif [ -f "$OPTARG" ]; then
               echo "No execute permssions for $OPTARG." 2>&1
	       exit 1
           else
               echo "Valid encp not given.  ($OPTARG)" 2>&1
	       exit 1
           fi;;
	h) print_help; exit 0;;
	d) debug=`expr $debug + 1`;;  #The more -d's, the more output.
        t) truncate_output=yes;; #Truncate after each test.  (default)
        a) truncate_output=no;; #Keep appending output from each test.
        n) number=$OPTARG;;  #Number of passes to run.
        s) simultaneous=$OPTARG;;  #Number of tests in each pass.
        c) cleanup=yes;;  #Remove any other output from pervious other tests.
        q) debug=0;;  #Silence the debug output.
	l) export LOCAL_DIR=$OPTARG;; #Set this from command line.
	p) export PNFS_DIR=$OPTARG;;  #Set this from command line.
    esac
done

#Clear any switches from the argument list so that we can continue processing
# all arguments on the command line.
shift `expr $OPTIND - 1`

#Make sure number is really a number or unlimited.  The unlimited value came
# from the ulimit command.  Exit on error.
if [ $number != unlimited ]; then
    is_integer_argument $number
fi
#Verify this is a number.  Exit on error.
is_integer_argument $simultaneous

#If the number of arguments, $#, is zero run all the tests.
if [ $# -eq 0 ]; then
    default=yes  #Run all tests.
else
    default=no  #Run the selected test(s)
fi

#Set the defaults for each test.
for test_name in `echo "$list_of_encp_tests" "$list_of_other_tests"`; do
    export $test_name=$default
done
###########################################################################
# Some tests are disabled or defaulted to off even if all tests should run.
###########################################################################
#Setuid tests are a security threat, since a setuid program is required
# to drive the test.
setuid_read_write_test=no
#The pipe_write feature has not been supported in encp.
pipe_write_test=no
#Set the skip-pnfs test off by default.  This test needs all PNFS/Chimera
# mount points unmounted.
skip_sfs_read_test=no
#The get & put tests do not work, since get and put don't work correctly.
#Luckily they are not used in production.
get_volume_test=no
get_put_test=no
###########################################################################
#Set the user picked tests.
if [ $# -ne 0 ]; then
    for argument in $*; do
        #Make sure the tests are defined.
	echo "$list_of_encp_tests" "$list_of_other_tests" | \
	    grep -E "^ *$argument *$" > /dev/null 2>&1

	if [ $? -ne 0 ]; then
	    echo No such test: $argument
	    exit 1
	else
	    export $argument=yes
	fi
    done
fi

#LOCAL_DIR is set by the user in their environment or they used -l.
if [ -z "$LOCAL_DIR" ]; then
    echo "\$LOCAL_DIR not set.  Stopping test." 1>&2
    exit 1
fi    
if [ ! -d "$LOCAL_DIR" ]; then
    echo "$LOCAL_DIR does not exist.  Stopping test." 1>&2
    exit 1
fi
#PNFS_DIR is set by the user in their environment or they used -p.
if [ $skip_sfs_read_test = yes ]; then
    if [ -d "$PNFS_DIR" ]; then
	echo "skip_sfs_read_test enabled and $PNFS_DIR exists.  Stopping test." 1>&2
	exit 1
    fi
elif [ -z "$PNFS_DIR" ]; then
    echo "\$PNFS_DIR not set.  Stopping test." 1>&2
    exit 1
elif [ ! -d "$PNFS_DIR" ]; then
    echo "$PNFS_DIR does not exist.  Stopping test." 1>&2
    exit 1
fi

#Get the functions to run in the following tests.
source encp_test_functions

#For simplicity, the user only needs to supply the location of the encp
# executable (or python file).  We can find the other commands, if available.
# The variables $enstore_cmd, $ensync_cmd, etc. are set.
find_command enstore
find_command ensync
find_command volume_assert
find_command get
find_command put
find_command enmv

#Hack to catch enstore errors universally in the tests.
try_enstore_cmd="try_enstore $enstore_cmd"
enstore_cmd="run_enstore $enstore_cmd"

#Note: REMOTE_ENCP is an environmental variable that tells encp to use
# pnfs_agent instead of PNFS directly.  We check for the same variable
# here to handle running these tests through the pnfs agent too.
if [ -n "$REMOTE_ENCP" ]; then
    $enstore_cmd pnfs_agent --timeout 10 --retries 3 --alive
    if [ $? -ne 0 ]; then
	echo 'pnfs_agent is not running and $REMOTE_ENCP is set.' \
	    'Stopping test.' 1>&2
	exit 1
    fi
fi

#Create the test area directories.
setup_local_test_paths
#Create the local test files or determine that they already exist.
encp_create_tests
#We don't want to make test files if testing --skip-pnfs.
if [ $skip_sfs_read_test = no ]; then
    #Create the test area directories.
    setup_storage_test_paths
    #Copy the local test files to PNFS for the read-only tests.
    copy_test_files
    if [ $cleanup = yes ]; then
        #Delete test output files from previously killed tests.
	cleanup_storage_test_paths
    fi
fi
if [ $cleanup = yes ]; then
    #Delete all existing encp output log files.
    cleanup_encp_output
    #Delete test output files from previously killed tests.
    cleanup_local_test_paths
fi

#Run the number of tests requested.  It would be nice to combine the two
# while statements, but "test expr1 -o expr2" is always executing expr2
# even when it doesn't need to.
loops=1
exit_status=0
if [ $number = "unlimited" ]; then
    while [ $exit_status -eq 0 ]; do
        if [ $debug -eq $DEBUG_SUMMARY ]; then
            echo "Starting test pass $loops."
        fi
	
	run_test_pass
	exit_status=$?

	if [ $debug -eq $DEBUG_SUMMARY ]; then
            echo "Completed test pass $loops.  (RC=$exit_status)"
        fi

	loops=$((loops + 1))	
    done
else
    while [ $loops -le $number -a $exit_status -eq 0 ]; do
        loop_message="Starting test pass $loops."
        if [ $debug -ge $DEBUG_SUMMARY ]; then
            echo $loop_message
        elif [ $debug -ge $DEBUG_EXECUTIVE_SUMMARY -a $number -gt 1 ]; then
            echo $loop_message
        fi
   
	run_test_pass
	exit_status=$?

	loop_message="Completed test pass $loops.  (RC=$exit_status)"
        if [ $debug -ge $DEBUG_SUMMARY ]; then
            echo $loop_message
        elif [ $debug -ge $DEBUG_EXECUTIVE_SUMMARY -a $number -gt 1 ]; then
            echo $loop_message
        fi

	loops=$((loops + 1))
    done
fi

exit $exit_status
