#! /bin/sh --posix

# $Id$

#Sourced from encp_test_script to run encp regression tests.
#
# Requires $ENSTORE_DIR/tools/encp_create_tests to work.
# Requires $LOCAL_DIR and $PNFS_DIR to be set.
#
# It creates directories test_files_for_${username} and
# encp_test_for_${username} in both $LOCAL_DIR AND $PNFS_DIR.

#These variables can be overridden from the encp_test_script command line.
encp_cmd=${encp_cmd:-`which encp`}
debug=${debug:-1}

username=$(id -u -n)
hostname=$(uname -n)

DEBUG_EXECUTIVE_SUMMARY=0
DEBUG_SUMMARY=1
DEBUG_DETAILED_SUMMARY=2
DEBUG_CLEANUP=3
DEBUG_ENCP_OUTPUT=4  #Lots of output.
DEBUG_SCAN_OUTPUT=4  #Lots of output.
DEBUG_CLEANUP_MORE=5  #Lots of output when the tests deadlock.

#############################################################################

find_command()
{
# $1 = The name of the command to find.
# Likely names are: enstore, get, put, volume_assert, ensync

    #Substitute in the name where encp is.  This preserves looking for
    # names like enstore_admin when encp_admin was listed on the command
    # line.
    this_cmd=`dirname $encp_cmd`/`basename $encp_cmd | sed "s/encp/$1/"`
    if [ -x "$this_cmd" ]; then
	export ${1}_cmd=$this_cmd
	return
    fi
    #Try again looking to see if there is a .py file instead.
    this_cmd=${this_cmd}.py
    if [ -x "$this_cmd" ]; then
        export ${1}_cmd=$this_cmd
        return
    fi
    #Simple replace the name this time.
    this_cmd=`dirname $encp_cmd`/$1
    if [ -x "$this_cmd" ]; then
	export ${1}_cmd=$this_cmd
	return
    fi
    #Try again looking to see if there is a .py file instead.
    this_cmd=${this_cmd}.py
    if [ -x "$this_cmd" ]; then
	export ${1}_cmd=$this_cmd
	return
    fi
}

#Either correct or append ENSTORE_CONFIG_[HOST|PORT] in the enstore.conf file.
correct_config_file()
{
    line_name=$1  #The string ENSTORE_CONFIG_HOST or ENSTORE_CONFIG_PORT.
    config_file_name=$2  #/tmp/enstore.conf

    #Get the value of the variable name stored in $line_name.
    value=$(eval echo \$$(echo $line_name))

    if [ -z "$value" ]; then
	grep ${line_name}= "$config_file_name" > /dev/null
	if [ $? -eq 0 ]; then
	    #The test copy of the enstore.conf file has this line already
	    # set and no environmental variable to override it was found.
	    return 0
	else
	    #The line was not in the enstore.conf config file already.
	    return 1
        fi
    fi

    #Make a temporary copy.
    tmp_config_file_name=${config_file_name}.tmp

    grep ${line_name}= "$config_file_name" > /dev/null
    if [ $? -eq 0 ]; then
	#We found an alrady present line; replace it.
	sed "s/$line_name=.*/$line_name=$value/" "$config_file_name" > "$tmp_config_file_name"
	if [ $? -ne 0 ]; then
            return 1
	fi
	mv $tmp_config_file_name $config_file_name
	if [ $? -ne 0 ]; then
            return 1
	fi
    else
	#No line found, add one at the end.
	env | grep $line_name >> "$config_file_name"
	if [ $? -ne 0 ]; then
            return 1
	fi
    fi

    return 0  #Success
}
#############################################################################

#Return true (zero) if the requested directory is a PNFS directory.
is_pnfs()
{
    if [ -n "$REMOTE_ENCP" ]; then
	$enstore_cmd pnfs_agent --exists "$1"
    else
	#It would be simple if frozen versions of the enstore command
	# had the command
	#$enstore_cmd sfs --database "$1"
	# Since they all don't we need to do this the hard way.
	cat "$1/.(tags)()" > /dev/null 2>&1
    fi
    return $?
}

#If the argument is a lock file (.lock.), return success (0).  Otherwise
# return 1.
is_lock_file()
{
    if [ `basename "$1" | cut -c 1-6` = ".lock." ]; then
	#Handle the case where the lock file is one of the target files.
	# This will happen for tests that only read files from a volume.
	return 0
    else
	return 1
    fi
}

#If the argument is a lock file (.lock.temp), return success (0).  Otherwise
# return 1.
is_temp_lock_file()
{
    if [ `basename "$1" | cut -c 1-10` = ".lock.temp" ]; then
	#Handle the case where the lock file is one of the target files.
	# This will happen for tests that only read files from a volume.
	return 0
    else
	return 1
    fi
}

#Make a non-PNFS or PNFS file.
make_file()
{
    is_pnfs `dirname "$1"`
    if [ $? -eq 0 ]; then
	make_pnfs_file "$1"
    else
	make_regular_file "$1"
    fi
    return $?
}

#Non-PNFS/Chimera.
make_regular_file()
{
    make_pre_message "$1"
    rc=$?
    if [ $rc -ne 0 ]; then
	return $rc
    fi
    
    touch "$1"
    make_save=$?

    make_post_message "$1"
    
    return $make_save
}

#Make a regular PNFS file.
make_pnfs_file()
{
    make_pre_message "$1"
    rc=$?
    if [ $rc -ne 0 ]; then
	return $rc
    fi

    if [ -n "$REMOTE_ENCP" ]; then
	$enstore_cmd pnfs_agent --touch "$1"
        make_save=$?
    else
        for lc in 1 2 3; do
	    #PNFS gives false ENOENT errors.  Retry them for a while.
            touch "$1" 2> /dev/null
            make_save=$?
            if [ $make_save -eq 0 ]; then
                break
            fi
            sleep 1
        done
        if [ $make_save -ne 0 ]; then
	    # One last time to give the user the error.
            touch "$1"
            make_save=$?
        fi
    fi
    
    make_post_message "$1"

    return $make_save
}

#echo common message for make_regular_file() and make_pnfs_file().
make_pre_message()
{
    if [ $simultaneous -gt 1 ]; then
	test_name="($section/$loops/$j)"
    else
	test_name=
    fi

    is_lock_file "$1"
    if [ $? -eq 0 ]; then
	is_temp_lock_file "$1"
	if [ $? -ne 0 ]; then
	    if [ -f "$1" ]; then
		write_cleanup "ALREADY MADE LOCK FILE $test_name $1" 1>&2
		return 1  #Error
	    else
		write_cleanup "MAKING LOCK FILE $test_name $1" 1>&2
	    fi
	fi
    else
	if [ -f "$1" ]; then
	    write_cleanup "ALREADY MADE FILE $test_name $1" 1>&2
	    return 1 #Error
	else
	    write_cleanup "MAKING FILE $test_name $1" 1>&2
	fi
    fi

    return 0  #Success.
}

#echo common message for make_regular_file() and make_pnfs_file().
make_post_message()
{
    if [ $simultaneous -gt 1 ]; then
	test_name="($section/$loops/$j)"
    else
	test_name=
    fi

    if [ ! -f "$1" ]; then
	write_cleanup "MADE FILE DOES NOT EXIST $test_name $1" 1>&2
    fi
}

#Handle making files in PNFS through mountpoint or pnfs_agent.
make_pnfs_dir()
{
    if [ -n "$REMOTE_ENCP" ]; then
	$enstore_cmd pnfs_agent --mkdirs "$1"
    else
        mkdir -p "$1"
    fi
    return $?
}

#Handle making symbolic links in PNFS through mountpoint or pnfs_agent.
#
link_file()
{
    # $1 is the target
    # $2 is the link name

    ln_save=0

    is_pnfs $(dirname "$1")
    if [ $? -eq 0 ]; then
	link_pnfs_file "$@"
	ln_save=`expr $ln_save + $?`
    else
	link_regular_file "$@"
	ln_save=`expr $ln_save + $?`
    fi

    return $ln_save
}

#
link_regular_file()
{
    # $1 is the target
    # $2 is the link name

    ln_pre_message "$@"
    rc=$?
    if [ $rc -eq 0 -o $rc -eq 1 ]; then
	#Already made this link (0) or another temporary file has this
        #link (1).
	return $rc
    elif [ $rc -eq 2 ]; then
        echo -n  #fall through to make link
    else
        return 1
    fi
    
    ln "$1" "$2" 2> /dev/null
    link_save=$?

    ln_post_message "$@"
    rc=$?
    
    if [ $rc -ne $link_save ]; then
	echo "Mismatched link status:" ln $link_save test $rc "$1" "$2" > /dev/tty
	ls -i "$1" "$2" > /dev/tty
    fi

    #return $link_save || $rc
    return $rc
}

#
link_pnfs_file()
{
    # $1 is the target
    # $2 is the link name

    ln_pre_message "$@"
    rc=$?
    if [ $rc -eq 0 -o $rc -eq 1 ]; then
	#Already made this link (0) or another temporary file has this
        #link (1).
	return $rc
    elif [ $rc -eq 2 ]; then
        echo -n  #fall through to make link
    else
        return 1
    fi

    if [ -n "$REMOTE_ENCP" ]; then
	#$enstore_cmd pnfs_agent --ln "$1" "$2"
	#ln_save=$?
	echo "Using pnfs_agent to make links is not supported." 1>&2
	exit 1
    else
        ln "$1" "$2" 2> /dev/null
	ln_save=$?
    fi

    ln_post_message "$@"
    rc=$?
    
    if [ $rc -ne $ln_save ]; then
	echo "Mismatched link status:" ln $ln_save test $rc "$1" "$2" > /dev/tty
	ls -i "$1" "$2" > /dev/tty
    fi

    #return $ln_save || $rc
    return $rc
}

#echo common message for link_regular_file() and link_pnfs_file().
ln_pre_message()
{
    # $1 is the target
    # $2 is the link name

    if [ $simultaneous -gt 1 ]; then
	test_name="($section/$loops/$j)"
    else
	test_name=
    fi
    is_lock_file "$2"
    if [ $? -eq 0 ]; then
	print_lock="LOCK"
    fi

    inode_1=$(ls -i $1 2> /dev/null | awk '{print $1}')
    inode_2=$(ls -i $2 2> /dev/null | awk '{print $1}')
    if [ -n "$inode_2" -a "$inode_1" = "$inode_2" ]; then
	ln_message=$(echo ALREADY MADE $print_lock LINK $test_name $2 -> $1)
	ln_rtn=0
    elif [ -n "$inode_2" -a "$inode" != "$inode_2" ]; then
	ln_message=$(echo SKIPPING $print_lock LINK $test_name $2 -> $1)
	ln_rtn=1
    else
	ln_message=$(echo MAKING $print_lock LINK $test_name $2 -> $1)
	ln_rtn=2
    fi

    is_temp_lock_file "$1"
    if [ $? -ne 0 ]; then
	#Don't overwhelm with output.
	write_cleanup "$ln_message" 1>&2
    fi

    return $ln_rtn
}

#echo common message for link_regular_file() and link_pnfs_file().
ln_post_message()
{
    # $1 is the target
    # $2 is the link name

    if [ $simultaneous -gt 1 ]; then
	test_name="($section/$loops/$j)"
    else
	test_name=
    fi
    is_lock_file "$2"
    if [ $? -eq 0 ]; then
	print_lock="LOCK"
    fi
    
    inode_1=$(ls -i $1 2> /dev/null | awk '{print $1}')
    inode_2=$(ls -i $2 2> /dev/null | awk '{print $1}')
    if [ -n "$inode_1" -a -n "$inode_2" -a "$inode_1" = "$inode_2" ]; then
	write_cleanup "MADE $print_lock LINK $test_name $2 -> $1"
	return 0  #Success
    fi
    
    #Don't overwhelm with output.
    return 1  #Error
}

#Handle removing a PNFS or non-PNFS file.  For convenience, accept a list
# of files.
rm_file()
{
    rtn_save=0

    for delete_name in "$@"; do
        is_pnfs $(dirname "$delete_name")
	if [ $? -eq 0 ]; then
	    rm_pnfs_file "$delete_name"
	    rtn_save=`expr $rtn_save + $?`
	else
	    rm_regular_file "$delete_name"
	    rtn_save=`expr $rtn_save + $?`
	fi
    done
    return $rtn_save
}

#Non-PNFS/Chimera.
rm_regular_file()
{
    rm_pre_message "$1"

    rm -f "$1"
    rm_save=$?

    rm_post_message "$1"

    return $rm_save
}

#Handle removing a pnfs file.
rm_pnfs_file()
{
    rm_pre_message "$1"

    if [ -n "$REMOTE_ENCP" ]; then
	$enstore_cmd pnfs_agent --remove "$1"
	rm_save=$?
    else
        rm -f "$1"
	rm_save=$?
    fi

    rm_post_message "$1"

    return $rm_save
}

#echo common message for rm_regular_file() and rm_pnfs_file().
rm_pre_message()
{
    if [ $simultaneous -gt 1 ]; then
	test_name="($section/$loops/$j)"
    else
	test_name=
    fi
    is_lock_file "$1"
    if [ $? -eq 0 ]; then
	is_temp_lock_file "$1"
	if [ $? -ne 0 ]; then
	    #Don't overwhelm with output.
	    if [ ! -f "$1" ]; then
		write_cleanup "ALREADY REMOVED LOCK FILE $test_name $1" 1>&2
	    else
		write_cleanup "REMOVING LOCK FILE $test_name $1" 1>&2
	    fi
	fi
    else
	if [ ! -f "$1" ]; then
	    write_cleanup "ALREADY REMOVED FILE $test_name $1" 1>&2
	else
	    write_cleanup "REMOVING FILE $test_name $1" 1>&2
	fi
    fi
}

#echo common message for rm_regular_file() and rm_pnfs_file().
rm_post_message()
{
    if [ $simultaneous -gt 1 ]; then
	test_name="($section/$loops/$j)"
    else
	test_name=
    fi
    
    if [ -f "$1" ]; then
	write_cleanup "REMOVED FILE STILL EXISTS $test_name $1" 1>&2
    fi
}

#Handle cleanup of files (both normal and in pnfs).
cleanup_files()
{
    #The list of files is called with '$cleanup' so we need to perform
    # the substitution here with eval.  $cleanup changes during the tests,
    # evaluting it here guarantees we have the latest list.
    for file in `eval echo $*`; do
        if [ "$file" = "/dev/null" ]; then
            continue
        fi

	#Automatically, remove lock files.
	is_lock_file "$file"
	if [ $? -eq 0 ]; then
	    #Handle the case where the lock file is one of the target files.
	    # This will happen for tests that only read files from a volume.
	    lock_file=$file
	    file=
	else
	    lock_file=$(get_lock_file_name "$file")
	fi

	#First, the normal file.
	if [ -f "$file" -o -n "$REMOTE_ENCP" ]; then
	    rm_file "$file"
	fi

	#Next, the lock file.
	if [ -f "$lock_file" -o -n "$REMOTE_ENCP" ]; then
	    rm_file "$lock_file"
	fi
    done
}

#Remove the files in the directories passed in.  Leave the directories.
cleanup_dir()
{
    for dir in `eval echo $*`; do
        if [ -d "$dir" ]; then
	    #TO DO:  Cleanup any non-regular files too.
	    cleanup_files $(get_file_list "$dir")
        fi
    done
}

#Return zero if the file exists, and one otherwise.
does_file_exist()
{
    if [ -n "$REMOTE_ENCP" ]; then
        $enstore_cmd pnfs_agent --exists "$1"
    else
        test -f "$1"
    fi
    return $?
}

#Return zero if the file is old, and one otherwise.
is_file_old()
{
    if [ -n "$REMOTE_ENCP" ]; then
	rc=1  #Say it is recent.  Might need to fix this sometime.
    else
	#We consider a file old after a day (-mtime +1).  Either another
	# test is hung while holding the lock file or another test
	# was killed and the locks not cleaned up.  Either way return
	# true (0) so we can move on.
	line_count=$(find "$1" -mtime +1 2> /dev/null | wc -l)
	if [ $line_count -gt 0 ]; then
	    rc=0
	else
	    rc=1
	fi
    fi
    return $rc
}

get_lock_file_name()
{
    rc=0
    for pathname in "$@"; do
	if [ -n "$pathname" ]; then
	    dname=`dirname $pathname`
	    fname=`basename $pathname`
	    lock_file="$dname/.lock.$fname"
	    echo $lock_file
	    rc=`expr $rc + 0`
	else
	    rc=`expr $rc + 1`
	fi
    done
    return $rc
}

get_lock_temp_file_name()
{
    #Grab the current process id.  In a subshell, $$ and $PPID give the
    # same answer as the current shell, thus the need to get the parent of
    # a child process to get the correct value.
    MYPID=$(sh -c 'echo $PPID')

    #Add a string specific to this proccess to the lock file.
    echo "$@" | sed "s:.lock.:.lock.temp${MYPID}.:"
}

#############################################################################

setup_log_file()
{
    #Grab the current process id.  In a subshell, $$ and $PPID give the
    # same answer as the current shell, thus the need to get the parent of
    # a child process to get the correct value.
    MYPID=$(sh -c 'echo $PPID')

    ENCP_OUTPUT=/tmp/encp_test_output_for_${username}
    output_lock_file=$(get_lock_file_name $ENCP_OUTPUT)
    output_lock_file_temp=$(get_lock_temp_file_name $output_lock_file)

    touch ${output_lock_file_temp} 2> /dev/null
    ln ${output_lock_file_temp} ${output_lock_file} 2> /dev/null
    rc=$?
    rm_file ${output_lock_file_temp}  #Cleanup.
    if [ $rc -eq 0 ]; then
        #We have the lock file.
	trap "all_done;" HUP INT QUIT ABRT ALRM TERM
	trap "all_done;" EXIT
    
	kill_children()
	{
echo "Killing pids" `$(jobs -p)` $saved_pids
	    for pid in $(jobs -p) $saved_pids; do
		echo "Killing $pid" 1>&2
		kill -s TERM $pid
	    done
	}

        #We have the common name of the output file since only this copy of
        # the script is running.
	all_done()
	{
	    rc=$?
	    if [ -n "$1" ]; then
		rc=$1  #Force error condition.
	    fi
	    ending_message $rc
	    kill_children
	    rm_file "${output_lock_file}"
	    trap "" HUP INT QUIT ABRT ALRM TERM  #clear the trap
	    trap "" EXIT
	    exit $rc
	}
    else

        #Another test script is running.  Use a different filename.
	ENCP_OUTPUT=${ENCP_OUTPUT}_${hostname}_$MYPID

        #We have a private version of the output file.
	all_done()
	{
	    rc=$?
	    if [ -n "$1" ]; then
		rc=$1
	    fi
	    ending_message $rc
	    exit $rc
	}
    fi
    write_cleanup ENCP_OUTPUT $ENCP_OUTPUT
    rm_file $ENCP_OUTPUT
    if [ $? -ne 0 ]; then
        #Use rm error message.
	all_done 1
    fi
    make_file $ENCP_OUTPUT
    if [ $? -ne 0 ]; then
        #Use touch error message.
	all_done 1
    fi
}

truncate_encp_output()
{
    #If the user wants all the tests attempted, then keep all of the output
    # in the output file from all the tests.  If the user only picked a
    # few tests, then truncate the output file to keep the output to
    # be looked at smaller.
    if [ $truncate_output = yes ]; then
        > $ENCP_OUTPUT    #truncate output file
    fi
}

cleanup_encp_output()
{
    write_cleanup "Starting cleanup of old output files."

    #Remove all existing encp regression test output.
    for file in $(ls /tmp/encp_test_output_for_${username}* 2>/dev/null); do
	rm_file $file
    done

    write_cleanup "Finished cleanup of old output files."
}

#############################################################################

#Print the start of the test.
print_test_name()
{
    test_name="STARTING $* TEST"

    write_summary $test_name
}

print_test_end()
{
# $1 = return value of the transfer function.
# $2 = expected exit status of the transfer function.

    use_rtn=$1
    use_expected_exit_status=$2

    if [ $use_rtn -ne $use_expected_exit_status ]; then
        print_message="$message TEST FAILED WITH $use_rtn INSTEAD OF $use_expected_exit_status ON $direction"
	write_summary "$print_message"
        if [ $debug -ge $DEBUG_ENCP_OUTPUT ]; then
            cat $ENCP_OUTPUT
        fi
        cleanup_files "$cleanup"
        all_done 1
    else
        print_message="$message TEST SUCCEEDED WITH $use_rtn ON $direction"
	write_summary "$print_message"
        if [ $debug -ge $DEBUG_ENCP_OUTPUT ]; then
            #Only output this if they really want it.
            cat $ENCP_OUTPUT
        fi
    fi
}

#This function preserves the value of $? after it is called.  This is called
# for all tests in a single pass within a single concurrent set of tests.
ending_message()
{
    rc=$?
    if [ -n "$1" ]; then
	rc="$1"
    fi
    if [ $rc -ne 0 ]; then
	end_message="See $ENCP_OUTPUT for full error."
    else
	end_message="Only successes for $ENCP_OUTPUT found."
    fi
    write_executive_summary "$end_message"
    return $rc
}

#Output to standard out or standard error.  Also output to the $OUTPUT_FILE
# if the value is defined.
write_output()
{
    fd=$1  #Should be 1 or 2 for stdout or stderr.
    shift
    debug_output_level=$1  #Should be one of $DEBUG_* constants.
    shift
    #TO DO:  Add checking of fd and debug_output_level.

    if [ $debug -ge $debug_output_level ]; then
	if [ -n "$ENCP_OUTPUT" ]; then
	    echo $* | tee -a "$ENCP_OUTPUT" 1>&${fd}
        else
	    echo $* 1>&${fd}
	fi
    else
	if [ -n "$ENCP_OUTPUT" ]; then
            #Just write to file
	    echo $* >> "$ENCP_OUTPUT"
	fi
    fi
}

write_executive_summary()
{
    write_output 1 $DEBUG_EXECUTIVE_SUMMARY $*
}
write_summary()
{
    write_output 1 $DEBUG_SUMMARY $*
}
write_detailed_summary()
{
    write_output 1 $DEBUG_DETAILED_SUMMARY $*
}
write_cleanup()
{
    write_output 1 $DEBUG_CLEANUP $*
}
write_encp_output()
{
    write_output 1 $DEBUG_ENCP_OUTPUT $*
}
write_scan_output()
{
    write_output 1 $DEBUG_SCAN_OUTPUT $*
}
write_cleanup_more()
{
    write_output 1 $DEBUG_CLEANUP_MORE $*
}

#############################################################################

has_scanfiles_command()
{
    help=$($enstore_cmd --help)

    echo "$help" | awk '{print $1}' | grep 'scanfiles' > /dev/null
    #If a match was found it has the command.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the command is not available.
    return 0
}

has_pnfs_agent_command()
{
    help=$($enstore_cmd --help)

    echo "$help" | awk '{print $1}' | grep 'pnfs_agent' > /dev/null
    #If a match was found it has the command.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the command is not available.
    return 0
}

has_mount_point_switch()
{
    if [ -n "$REMOTE_ENCP" ]; then
        #Current "enstore pnfs_agent --mount-point" is not defined.
	return 0
    else
	help=$($enstore_cmd sfs --help)
    fi

    echo "$help" | awk '{print $1}' | grep '\-\-mount-point' > /dev/null
    #If a match was found it has the command.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the command is not available.
    return 0
}

has_library_switch()
{
    help=$($encp_cmd --help)

    echo "$help" | awk '{print $1}' | grep '\-\-library' > /dev/null

    #If a match was found it has the switch.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the switch is not available.
    return 0
}

has_volume_switch()
{
    help=$($encp_cmd --help)

    echo "$help" | awk '{print $1}' | grep '\-\-volume' > /dev/null

    #If a match was found it has the switch.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the switch is not available.
    return 0
}

has_cache_switch()
{
    help=$($encp_cmd --help)

    echo "$help" | awk '{print $1}' | grep '\-\-get-cache' > /dev/null

    #If a match was found it has the switch.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the switch is not available.
    return 0
}

has_max_resubmits_switch()
{
    help=$($encp_cmd --help)

    echo "$help" | awk '{print $1}' | grep '\-\-max-resubmit' > /dev/null

    #If a match was found it has the switch.
    if [ $? -eq 0 ]; then
	return 1
    fi

    #Return zero if the switch is not available.
    return 0
}

is_admin_encp()
{
    version=$($encp_cmd --help)

    #This check only works for as long as --storage-group remains an
    # administator only option.
    echo "$version" | awk '{print $1}' | grep '\-\-storage-group' > /dev/null

    #If a match was found it is an admin version.
    if [ $? -eq 0 ]; then
	return 1
    fi

    return 0
}

is_user_encp()
{
    version=$($encp_cmd --help)

    #This check only works for as long as --get-cache remains an
    # dcache encp and above option.
    echo "$version" | awk '{print $1}' | grep '\-\-get-cache' > /dev/null

    #If a match was not found it is an user version.
    if [ $? -ne 0 ]; then
	return 1
    fi

    return 0
}

#The dcache version of encp (for pool nodes) is at times also called
# the user2 version of encp.
is_user2_encp()
{
    version=$($encp_cmd --help)

    #This check only works for as long as --get-cache remains an
    # dcache encp and above option.
    echo "$version" | awk '{print $1}' | grep '\-\-get-cache' > /dev/null

    #If a match was found it might be a dcache version.
    if [ $? -eq 0 ]; then
	echo "$version" | awk '{print $1}' | grep '\-\-storage-group' > /dev/null

        #If a match was not found it is a dcache version.
	if [ $? -ne 0 ]; then
	    return 1
	fi
    fi

    return 0
}

#############################################################################

setup_local_test_paths()
{
    #Include the username so multiple users' can run their own regression tests
    # on the same node at the same time.
    LOCAL_INPUT_DIR="$LOCAL_DIR/test_files_for_${username}"
    LOCAL_OUTPUT_DIR="$LOCAL_DIR/encp_test_for_${username}"
    ENSYNC_INPUT_DIR="$LOCAL_INPUT_DIR/ensync_test"
    
    mkdir -p "$LOCAL_INPUT_DIR"
    mkdir -p "$LOCAL_OUTPUT_DIR"
    mkdir -p "$ENSYNC_INPUT_DIR"

    verify_permissions "$LOCAL_INPUT_DIR" "$LOCAL_OUTPUT_DIR" "$ENSYNC_INPUT_DIR"
}

setup_storage_test_paths()
{
    #Include the username so multiple users' can run their own regression tests
    # on the same node at the same time.
    PNFS_INPUT_DIR="$PNFS_DIR/test_files_for_${username}"
    PNFS_OUTPUT_DIR="$PNFS_DIR/encp_test_for_${username}"
    PNFS_AGENT_OUTPUT_DIR="$PNFS_OUTPUT_DIR"
    ENSYNC_OUTPUT_DIR="$PNFS_OUTPUT_DIR/ensync_test"

    make_pnfs_dir "$PNFS_INPUT_DIR"
    make_pnfs_dir "$PNFS_OUTPUT_DIR"
    make_pnfs_dir "$ENSYNC_OUTPUT_DIR"
    
    verify_permissions "$PNFS_INPUT_DIR" "$PNFS_OUTPUT_DIR" "$ENSYNC_OUTPUT_DIR"
}

verify_permissions()
{
    #Make sure we have correct permissions for these directories.
    for dir_to_check in "$@"; do
        if [ ! -x "$dir_to_check" ]; then
	    echo "No execute permissions for directory: $dir_to_check" 1>&2
	    all_done 1
	fi
	if [ ! -r "$dir_to_check" ]; then
	    echo "No read permissions for directory: $dir_to_check" 1>&2
	    all_done 1
	fi
	if [ ! -w "$dir_to_check" ]; then
	    echo "No write permissions for directory: $dir_to_check" 1>&2
	    all_done 1
	fi
    done
}

#Find and cleanup leftover files from previous abnormally terminated tests.
cleanup_local_test_paths()
{
    write_cleanup "Starting cleanup of old local test files."

    #Cleanup failed output files in local test directory.
    filelist=$(find "$LOCAL_OUTPUT_DIR" -maxdepth 1 -type f 2> /dev/null)
    #Cleanup failed output files in local test directory for
    # single_local_pnfs_path_read_test.
    filelist2=$(find "$LOCAL_OUTPUT_DIR/pnfs" -maxdepth 1 -type f 2> /dev/null)
    echo "$filelist" "$filelist2" |
    while read line; do
	if [ -z "$line" ]; then
            continue
        fi
	rm_regular_file "$line"
    done

    
    #Cleanup the local .lock. files still lying around.
    filelist=$(find "$LOCAL_INPUT_DIR" -maxdepth 1 -type f -name '.lock.*' 2> /dev/null)
    echo "$filelist" |
    while read line; do
	if [ -z "$line" ]; then
	    continue
	fi
	rm_regular_file "$line"
    done

    write_cleanup "Finished cleanup of old local test files."
}

#Find and cleanup leftover files from previous abnormally terminated tests.
cleanup_storage_test_paths()
{
    write_cleanup "Starting cleanup of old storage test files."

    #Cleanup failed output files in test PNFS directory.
    if [ -n "$REMOTE_ENCP" ]; then
	filelist=$($enstore_cmd pnfs_agent --just-files --list-dir "$PNFS_OUTPUT_DIR")
    else
        filelist=$(find "$PNFS_OUTPUT_DIR" -maxdepth 1 -type f 2> /dev/null)
	if [ -z "$filelist" ]; then
	    #32 bit find running against 64 bit Chimera fails with a:
	    #    Value to large for defined data type
	    #error.  Try this as a work around.
            filelist=$(ls -1p $PNFS_OUTPUT_DIR | grep -v "/" | tr -s " " " " | cut -f 9- -d " " | sed "s:^:$PNFS_OUTPUT_DIR/:" | tr -s "/" "/")
        fi
    fi
    echo "$filelist" |
    while read line; do
        if [ -z "$line" ]; then
            continue
        fi
	rm_pnfs_file "$line"  #Use function for pnfs_agent cases.
    done

    
    #Cleanup the PNFS/Chimera .lock. files still lying around.
    if [ -n "$REMOTE_ENCP" ]; then
	
	filelist=$($enstore_cmd pnfs_agent --just-files --list-dir "$PNFS_INPUT_DIR" | grep .lock.)
    else
        filelist=$(find "$PNFS_INPUT_DIR" -maxdepth 1 -type f -name '.lock.*' 2> /dev/null)
	if [ -z "$filelist" ]; then
            #32 bit find running against 64 bit Chimera fails with a:
	    #    Value to large for defined data type
	    #error.  Try this as a work around.
            filelist=$(ls -1p $PNFS_INPUT_DIR/.lock.* 2> /dev/null)
        fi
    fi
    echo "$filelist" |
    while read line; do
        if [ -z "$line" ]; then
            continue
        fi
	rm_pnfs_file "$line"  #Use function for pnfs_agent cases.
    done

    write_cleanup "Finished cleanup of old storage test files."
}

#Use encp to copy any local test files into the PNFS directory where these
# test files should be copied to for the read-only tests to work.
copy_test_files()
{
    #Copy local test files into PNFS/Chimera.
    for fname in $(ls $LOCAL_INPUT_DIR); do
        #Handle using mounted pnfs filesystem or using pnfs agent.
	if [ -n "$REMOTE_ENCP" ]; then
	    $enstore_cmd pnfs_agent --exists $PNFS_INPUT_DIR/$fname
	    pnfs_test=$?
	else
	    test -f $PNFS_INPUT_DIR/$fname
	    pnfs_test=$?
	fi
	if [ -f $LOCAL_INPUT_DIR/$fname -a $pnfs_test -ne 0 ]; then
	    #We set the file family to volume_read_test for the benifit of the
	    # volume read test.
	    echo encp --file-family volume_read_test $LOCAL_INPUT_DIR/$fname $PNFS_INPUT_DIR/$fname
	    encp --file-family volume_read_test $LOCAL_INPUT_DIR/$fname $PNFS_INPUT_DIR/$fname
	fi
    done
}

#############################################################################

get_file_list()
{
#$1 = directory of file to choose from

    #Restrict this to files less than 100MB in size and non-hidden files.
    # Only consider files in this directory first; go recurisive if the
    # first list is empty.
    if [ -d $1 ]; then
        filenames=$(find $1 -maxdepth 1 -size -104857600c -type f 2> /dev/null)
        if [ -z "$filenames" ]; then
	    filenames=$(find $1 -size -104857600c -type f ! -name ".*" 2> /dev/null)
        fi
    elif [ -n "$REMOTE_ENCP" -a $(is_pnfs "$1") ]; then
        filenames=$($enstore_cmd pnfs_agent --just-files --list-dir "$1")
    fi

    echo "$filenames"
}

get_pnfs_file_list()
{
#$1 = directory of file to choose from

    #Restrict this to files less than 100MB in size and non-hidden files.
    # Only consider files in this directory first; go recurisive if the
    # first list is empty.
    if [ -n "$REMOTE_ENCP" ]; then
	filenames=$($enstore_cmd pnfs_agent --just-files --list-dir "$1")
    else
        filenames=$(find "$1" -maxdepth 1 -size -104857600c -type f ! -name ".*" 2> /dev/null)
	if [ -z "$filenames" ]; then
            #32 bit find running against 64 bit Chimera fails with a:
	    #    Value to large for defined data type
	    #error.  Try this as a work around.
            filenames=$(ls -1p $1 2> /dev/null | grep -v "/" | tr -s " " " " | cut -f 9- -d " " | sed "s:^:$1/:" | tr -s "/" "/")
        fi
	if [ -z "$filenames" ]; then
	    filenames=$(find $1 -size -104857600c -type f ! -name ".*" 2> /dev/null)
	fi
    fi

    echo "$filenames"
}

get_volume_from_filename()
{
#$1 = pnfs filename to get the volume
    filename=$1
    
    
    if [ -n "$REMOTE_ENCP" ]; then
	#Rip just the volume out of the layer 4.
	volume=$($enstore_cmd pnfs_agent --layer 4 $filename | sed -n '1p')
    else
        #Determine the layer 4 filename.
	layer4_filename=$(dirname $filename; echo "/.(use)(4)("; basename $filename; echo ")")
	layer4_filename=$(echo $layer4_filename | tr -d " ")
	
        #Rip just the volume out of the layer 4.
	volume=$(cat $layer4_filename | sed -n '1p')
    fi

    echo $volume
}


#Make sure any debuging echos do not go to standard out.  This function returns
# volume labels that way any random output will give errors.
#
#It is possible that this function returns less than the requested number
# of volume labels depending on availability.
pick_random_volumes()
{
    number=$1  #First argument is number of volumes. Rest of arguments are volumes.
    shift
    rnd=`expr $RANDOM + 1`
    #Between 9 and number of volumes, pick the lesser.
    if [ 9 -lt $# ]; then
	i=9
    else
	i=$#
    fi
    rand=`expr $rnd % $i`
    rand=`expr $rand + 1`
    i=1
    while [ $i -le $number ]; do
        eval echo \$$rand
	shift
	i=`expr $i + 1`
    done
}

#Make an alias, since these functions would be the same.
alias pick_random_bfids=pick_random_volumes

#Make sure any debuging echos do not go to standard out.  This function returns
# filenames that way any random output will give errors.
#
#It is possible that this function returns less than the requested number
# of files when multiple test are running at once to avoid deadlocks.
pick_random_files()
{
    number=$1  #First argument is number of files. Rest of arguments are files.
    shift

    if [ $# -eq 0 ]; then
	echo "No files available for selection." 1>&2
	return 0
    fi

    rnd=`expr $RANDOM + 1`
    rand=`expr $rnd % $#`
    rand=`expr $rand + 1`
    current=$rand  #Seed the current position with the random number.
    i=0  #Number of files choosen for locking.

    #This outer loop is to make sure that as long as one file is locked when
    # more than one file needs to be picked, that we can return the shorter
    # list.  If we haven't gotten at least one file already then we keep
    # looping.
    while [ $i -eq 0 ]; do
      loop_count=0  #Number of passes over the list of files.
      while [ $i -lt $number -a $loop_count -lt 3 ]; do

	if [ $current -eq 0 ]; then
	    #Skip the executable in $0.
            loop_count=`expr $loop_count + 1`
	    current=1
	    sleep 1 #Give other encps a chance.
	fi

	filename=$(eval echo \$\{"${current}"\})
	dname=$(dirname $filename)
	fname=$(basename $filename)
	if [ $(echo "$fname" | cut -c 1) = "." ]; then
	    #We found a hidden file.  Skip it.
	    current=$(echo \( $current + 1 \) % $# | bc)
	    continue
	fi
	lock_file=$(get_lock_file_name $filename)
	lock_file_temp=$(get_lock_temp_file_name $lock_file)
	#Permorm check to make sure the files are different.
	if [ "$lock_file" = "$lock_file_temp=" -o \
             "$lock_file" = "$filename" ]; then
	    echo "Lock file can not be the same as the test file." 1>&2
	    exit 50
	fi

	make_file "$lock_file_temp" 1>&2
	
	#Determine if the file exists.
	#ln "$lock_file_temp" "$lock_file" 2> /dev/null
	link_file "$lock_file_temp" "$lock_file" 1>&2
	rc=$?
	rm_file "$lock_file_temp"  1>&2 #Cleanup.
	if [ $rc -eq 0 ]; then
	    #The lock file does not exist.
	    current=$(echo \( $current + 1 \) % $# | bc)
	    i=`expr $i + 1`  #Up to number of files found.
	    echo "$filename"
	else
	    #Determine if the file is new and should be skipped.  Or old
	    # and should be removed.
	    is_file_old "$lock_file"
	    if [ $? -eq 0 ]; then
		write_cleanup "Found old lock file.  Removing.  $lock_file" 1>&2
		rm_file "lock_file"
		current=`echo \( $current + 1 \) % $# | bc`
		i=`expr $i + 1`  #Up to number of files found.
		echo "$filename"
	    else
		#This test file is in use, get another one.
		write_cleanup_more "Found recent lock file.  Skipping.  $lock_file" 1>&2
		current=`echo \( $current + 1 \) % $# | bc`
		sleep 1  #Give other encps a moment to complete.
	    fi
	fi
      done
    done
    return $i
}

#First argument is the directory to place before every other argument.
absfile()
{
    dir=$1
    shift
    for s in $*
    do
	s=$(basename $s)
	abs_filenames=$(echo $abs_filenames; echo $dir/$s)
    done

    echo $abs_filenames
}

#############################################################################

#Run the supplied enstore command.  Automatically handle errors.
run_enstore()
{
    #Pass the command to run to the helper function, but we need to
    #swap stderr and stdout back to where they belong.
    __run_enstore "$@" 3>&1 1>&2 2>&3
}

#Run the supplied enstore command.  Automatically handle errors.
__run_enstore()
{
    #Run the command, but swap stderr and stdard out.
    s2=$("$@" 3>&1 1>&2 2>&3)
    rc=$?
    if [ $rc -ne 0 ]; then
	if [ -n "$ENCP_OUTPUT" ]; then
	    #These will be going to stderr once run_enstore reswaps
	    # stderr and stdout.
	    echo "$@" | tee -a "$ENCP_OUTPUT"
	    echo "$s2" | tee -a "$ENCP_OUTPUT" 
	else
	    #These will be going to stderr once run_enstore reswaps
	    # stderr and stdout.
	    echo "$@"
	    echo "$s2"
	fi
	exit $rc
    fi
}

try_enstore()
{
    result=$("$@" 2>&1)
    rc=$?
    if [ $rc -ne 0 ]; then
	if [ -z "$ENCP_OUTPUT" ]; then
	    echo "$@" | tee -a "$ENCP_OUTPUT" 1>&2
	    echo "$result" | tee -a "$ENCP_OUTPUT" 1>&2
	else
	    echo "$@" 1>&2
	    echo "$result" 1>&2
	fi
    else
	echo "$result"
    fi
    return $rc
}

#############################################################################

#transfer file
transfer()
{
    encp_command=`eval echo $1`
    infile=`eval echo $2`
    outfile=`eval echo $3`
    cleanup=`eval echo $4`
    options=`eval echo $5`
    message=`eval echo $6`
    direction=`eval echo $7`
    if [ -z "$8" ]; then  #This allows us to check for failures too.
        expected_exit_status=0
    else
        expected_exit_status=`eval echo $8`
    fi

    #
    #Send this debugging output to the file, or the file and terminal.
    #

    header_info=$( echo "ENCP: $encp_command"
        echo INPUT: $infile
        echo OUTPUT: $outfile
        echo INCLEANUP: $cleanup
        echo OPTIONS: $options
        echo MESSAGE: $message
        echo DIRECTION: $direction
        echo EXPECTED_EXIT_STATUS: $expected_exit_status
        #Output the type of encp that we are running.
	is_admin_encp
	if [ $? -eq 1 ]; then
            echo TYPE: "admin encp version"
        else
	    is_user2_encp
	    if [ $? -eq 1 ]; then
                echo TYPE: "dcache encp version"
            else
	        is_user_encp
	        if [ $? -eq 1 ]; then
                    echo TYPE: "user encp version"
                else
                    echo TYPE: "<unknown>"
                fi
           fi
        fi
        echo CWD: $(uname -n):$(pwd)
	)
    #Note: print_test_name() output logged from print_test_name().
    if [ $debug -ge $DEBUG_DETAILED_SUMMARY ]; then
	echo "$header_info" | tee -a $ENCP_OUTPUT 2>&1
        #Only include the command line header if -d was specified.  We
        # still include the command being tested with just one -d.
        echo -n COMMAND: "" | tee -a $ENCP_OUTPUT 2>&1
    else
	echo "$header_info" >> $ENCP_OUTPUT 2>&1
	echo -n COMMAND: "" >> $ENCP_OUTPUT 2>&1
    fi

    more_header_info=$(
	#Output the command line that will be executed.
	echo "$encp_command $verbose $options $infile $outfile >> $ENCP_OUTPUT 2>> $ENCP_OUTPUT"
	)
    if [ $debug -ge $DEBUG_DETAILED_SUMMARY ]; then
	echo "$more_header_info" | tee -a $ENCP_OUTPUT 2>&1
    else
        echo "$more_header_info" >> $ENCP_OUTPUT 2>&1
    fi


    #There are some errors that are likely transient.  We want to retry then.
    rtn=-1
    max_transfers=10
    attempted_transfers=0
    while [ $rtn -ne 0 -a $attempted_transfers -lt $max_transfers ]; do
	if [ $attempted_transfers -gt 0 ]; then
	    #We failed because someone bounced the Enstore servers.
	    #Wait awile and try again.
	    echo -e "\n\nRetrying in 60 seconds after $encp_error_status.\n\n"
	    sleep 60
	fi

	#
        # Run the command.
        #
        cmd_output=$($encp_command $verbose $options $infile $outfile 2>&1)
	rtn=$?
    
	echo "$cmd_output" >> $ENCP_OUTPUT 2>&1
	encp_error_line=$(echo "$cmd_output" | grep STATUS=)
	encp_error_status=$(echo $encp_error_line | sed 's/STATUS=//')
	
	attempted_transfers=$((attempted_transfers + 1))

	if [ "$encp_error_status" != "CONFIGDEAD" -a \
	     "$encp_error_status" != "SERVERDIED" ]; then
	    #There might be others, just don't know what they are yet.
	    break
	fi
    done

    #
    # Did it work correctly?  (This calls exit on error.)
    #
    print_test_end $rtn $expected_exit_status
}

#############################################################################

#Test if the original input and the final output files are the same.
###
### This does does not work with pnfs_agent.
###
test_diff()
{
    infiles=`eval echo $1`
    outfiles=`eval echo $2`
    cleanupfiles=`eval echo $3`
    message_out=`eval echo $4`

    i=1
    count=`echo $infiles | wc -w`
    while [ $i -le $count ]; do
	ifile=`echo $infiles | cut -d" " -f$i`
	ofile=`echo $outfiles | cut -d" " -f$i`
	i=`expr $i + 1`

	diff_output=`diff --brief $ifile $ofile 2>&1`

	rtn=$?
	if [ "$rtn" -gt 0 ]; then
	    #The files are not the same.  This might be correct if we used
	    # a null mover.

	    o_ls_size=`ls -l "$ofile" | awk '{print $5}'`
	    i_ls_size=`ls -l "$ifile" | awk '{print $5}'`
	    if [ $i_ls_size -eq $o_ls_size ]; then
		non_null_word_count=`cat "$ofile" | tr -d "\000" | wc -c`
		if [ $non_null_word_count -eq 0 ]; then
		    #We have a NULL file.  Let's assume this is from a
		    # null mover.
		    return 0
		fi
	    fi

	    echo $message_out "TEST FAILED ON DIFF" | tee -a $ENCP_OUTPUT 2>&1
	    echo "$diff_output" | tee -a $ENCP_OUTPUT 2>&1
	    cat $ENCP_OUTPUT
	    cleanup_files '$cleanupfiles'
	    all_done 1
	fi
    done
}

#Test that the layer info is correct.
test_layer()
{
    pnfsfiles=`eval echo $1`
    message_out=`eval echo $2`
    
    for file in $pnfsfiles; do
	if [ -n "$REMOTE_ENCP" ]; then
            result=`$enstore_cmd pnfs_agent --layer 1 $file 2>&1`
        else
	    result=`$enstore_cmd sfs --layer $file 1 2>&1`
	fi
	rtn_value=$?
	if [ $rtn_value -ne 0 ]; then
	    echo $message_out "TEST FAILED ON LAYER" | tee -a $ENCP_OUTPUT 2>&1
	    echo No bfid value: $rtn_value: $result: $file | tee -a $ENCP_OUTPUT 2>&1
	    all_done 1
	fi
	if [ -n "$REMOTE_ENCP" ]; then
	    result=`$enstore_cmd pnfs_agent --layer 4 $file`
	else
	    result=`$enstore_cmd sfs --layer $file 4`
	fi
	for line in result; do
	    if [ $line = "unknown" ]; then
		echo $message_out "TEST FAILED ON LAYER" | tee -a $ENCP_OUTPUT 2>&1
		echo Layer 4 contains unknown value: $file | tee -a $ENCP_OUTPUT 2>&1
		echo $result | tee -a $ENCP_OUTPUT 2>&1
		all_done 1
	    fi
	done
    done
}

#Test that the permissions are the same.
###
### This does does not work with pnfs_agent.
###
permissions_test()
{
    infiles=`eval echo $1`
    outfiles=`eval echo $2`
    cleanupfiles=`eval echo $3`
    message_out=`eval echo $4`

    i=1
    count=`echo $infiles | wc -w`
    while [ $i -le $count ]; do
	ifile=`echo $infiles | cut -d" " -f$i`
	ofile=`echo $outfiles | cut -d" " -f$i`
	i=`expr $i + 1`

	result1=`ls -l $ifile | cut -c1-10`
	result2=`ls -l $ofile | cut -c1-10`
	
	if [ $result1 != $result2 ]; then
	    echo $message_out "TEST FAILED ON PERMISSIONS" | tee -a $ENCP_OUTPUT 2>&1
	    echo $result1 != $result2 | tee -a $ENCP_OUTPUT 2>&1
	    rm_file $cleanupfiles
	    all_sone 1
	fi
    done
}

#Test that the sizes are the same.
###
### This does does not work with pnfs_agent.
###
size_test()
{
    infiles=`eval echo $1`
    outfiles=`eval echo $2`
    cleanupfiles=`eval echo $3`
    message_out=`eval echo $4`

    i=1
    count=`echo $infiles | wc -w`
    while [ $i -le $count ]; do
	ifile=`echo $infiles | cut -d" " -f$i`
	ofile=`echo $outfiles | cut -d" " -f$i`
	i=`expr $i + 1`

	result1=`ls -l $ifile | sed 's/ \{1,30\}/ /g' | cut -f 5 "-d "`
	result2=`ls -l $ofile | sed 's/ \{1,30\}/ /g' | cut -f 5 "-d "`
	if [ $result1 != $result2 ]; then
	    echo $message_out "TEST FAILED ON SIZE" | tee -a $ENCP_OUTPUT 2>&1
	    echo $result1 != $result2 | tee -a $ENCP_OUTPUT 2>&1
	    rm_file $cleanupfiles || setuid rm_file $cleanupfiles
	    all_done 1
	fi
    done
}

#Test that the data access layer is correct.
data_access_layer_test()
{
    infiles=`eval echo $1`
    outfiles=`eval echo $2`
    cleanupfiles=`eval echo $3`
    message_out=`eval echo $4`
    volume1=`get_volume_from_filename "$infiles" 2> /dev/null`
    volume2=`get_volume_from_filename "$outfiles" 2> /dev/null`
    volume=`echo $volume1 $volume2`

    #If the INFILE data access output line does not specify the filename,
    # exit with error.
    grep INFILE "$ENCP_OUTPUT" | grep "$infiles" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	echo $message_out "TEST FAILED ON INFILE" | tee -a $ENCP_OUTPUT 2>&1
	grep INFILE "$ENCP_OUTPUT"
	echo Expected: "$infiles"
	rm_file $cleanupfiles || setuid rm_file $cleanupfiles
	all_done 1
    fi

    #If the OUTFILE data access output line does not specify the filename,
    # exit with error.
    grep OUTFILE "$ENCP_OUTPUT" | grep "$outfiles" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	echo $message_out "TEST FAILED ON OUTFILE" | tee -a $ENCP_OUTPUT 2>&1
	grep OUTFILE "$ENCP_OUTPUT"
	echo Expected: "$outfiles"
	rm_file $cleanupfiles || setuid rm_file $cleanupfiles
	all_done 1
    fi

    #If the VOLUME data access output line does not specify the volume,
    # exit with error.
    grep LABEL "$ENCP_OUTPUT" | grep "$volume" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	echo $message_out "TEST FAILED ON VOLUME" | tee -a $ENCP_OUTPUT 2>&1
	grep LABEL "$ENCP_OUTPUT"
	echo Expected: "$volume"
	rm_file $cleanupfiles || setuid rm_file $cleanupfiles
	all_done 1
    fi

    #If the LOCATION data access output line does not specify the position,
    # exit with error.
    lc=`grep LOCATION "$ENCP_OUTPUT" | tail -n 1 | sed 's/LOCATION=//' | wc -m`
    if [ $lc -eq 0 ]; then
	echo $message_out "TEST FAILED ON LOCATION" | tee -a $ENCP_OUTPUT 2>&1
	grep LOCATION "$ENCP_OUTPUT"
	echo Expected: non-empty string
	rm_file $cleanupfiles || setuid rm_file $cleanupfiles
	all_done 1
    fi
}

enstore_check_test()
{
    pnfsfiles=`eval echo $1`
    cleanupfiles=`eval echo $2`
    message_out=`eval echo $3`

    en_check "$pnfsfiles"
    if [ $? -ne 0 ]; then
	echo $message_out "TEST FAILED ON ENSTORE CHECK" | tee -a $ENCP_OUTPUT 2>&1
	rm_file $cleanupfiles || setuid rm_file $cleanupfiles
	all_done 1
    fi
}

#Run the enstore scan test on a list of files.
scan_test()
{
    has_scanfiles_command
    if [ $? -eq 0 ]; then
        # skip the test since "enstore scan" is not available.
	write_detailed_summary "'enstore scan' test is not available.  Continuing."
	return
    fi

    pnfsfiles=`eval echo $1`
    message_out=`eval echo $2`

    results=0
    for scan_filename in `echo "$pnfsfiles"`; do
        raw_scan_output=`$enstore_cmd scan $scan_filename 2>&1`
	write_scan_output "$enstore_cmd scan $scan_filename"
	write_scan_output "$raw_scan_output"
	this_scan_output=`echo $raw_scan_output | grep ' ... OK'`
        results=$((results + $?))
	scan_output=${scan_output}${this_can_output}
    done
    if [ $results -ne 0 ]; then
        echo $message_out "TEST FAILED ON SCAN CHECK" | tee -a $ENCP_OUTPUT 2>&1
	echo "$scan_output"
        all_done $results
    fi
}

##############################################################################
# The functions defined here are helper functions for running the tests.
##############################################################################

__read_test()
{
# $1 = read command; encp or get
# $2 = number of files to transfer
# $3 = test specific options
# $4 = expected test exit status

    print_test_name $section

    read_cmd=${1:-encp}  #Default to encp.
    number_of_files=${2:-1} #Default of 1.
    use_options=$3
    test_expected_exit_status=${4:-0} #Default of success.

    #Snag a random file.
    filelist=$(get_pnfs_file_list "$PNFS_INPUT_DIR")
    if [ -z "$filelist" ]; then
	echo PNFS_INPUT_DIR $PNFS_INPUT_DIR
	echo "Input directory empty.  Skipping test and continuing." 1>&2
	return
    fi
    #Specify file paths.
    filename=$(pick_random_files $number_of_files $filelist)
    outname=/dev/null
    cleanup="$outname $(get_lock_file_name $filename)"  #Make sure the lock file is last.

    transfer "$read_cmd" '$filename' '$outname' '$cleanup' "$use_options" "$section" READ $test_expected_exit_status

    cleanup_files '$cleanup'
}

__write_test()
{
# $1 = write command; encp or put
# $2 = number of files to transfer
# $3 = test specific options
# $4 = expected test exit status

    print_test_name $section

    read_cmd=${1:-encp}  #Default to encp.
    number_of_files=${2:-1} #Default of 1.
    use_options=$3
    test_expected_exit_status=${4:-0} #Default of success.

    #Snag a random file.
    filelist=$(get_pnfs_file_list "$LOCAL_INPUT_DIR")
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
	return
    fi
    #Specify file paths.
    filename=$(pick_random_files $number_of_files $filelist)
    basename=$(basename $filename)
    pnfsname=$(echo ${PNFS_OUTPUT_DIR}/$basename)
    cleanup="$pnfsname $(get_lock_file_name $filename)"  #Make sure the lock file is last.

    transfer "$read_cmd" '$filename' '$pnfsname' '$cleanup' "$use_options" "$section" WRITE $test_expected_exit_status

    if [ $test_expected_exit_status -eq 0 ]; then
	scan_test '$pnfsname' "$section"
    fi

    cleanup_files '$cleanup'
}

__read_write_test()
{
# $1 = read command; encp or get
# $2 = write command; encp or put
# $3 = number of files to transfer
# $4 = test specific options
# $5 = expected test exit status

    print_test_name $section

    read_cmd=${1:-encp}  #Default to encp.
    write_cmd=${2:-encp}  #Dfault to encp.
    number_of_files=${3:-1} #Default of 1.
    use_options=$4
    test_expected_exit_status=${5:-0} #Default of success.

    #Snag random files.
    filelist=$(get_file_list "$LOCAL_INPUT_DIR")
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
	return
    fi
    filenames=$(pick_random_files $number_of_files $filelist)
    pnfsnames=$(absfile $PNFS_OUTPUT_DIR $filenames)
    cleanup="$pnfsnames $(get_lock_file_name $filenames)"

    transfer $write_cmd '$filenames' '$PNFS_OUTPUT_DIR' '$cleanup' "$use_options" "$section" WRITE $test_expected_exit_status

    test_layer '$pnfsnames' "$section"
    scan_test '$pnfsnames' "$section"
    
    #Add the second direction.
    outnames=$(absfile $LOCAL_OUTPUT_DIR $filenames)
    cleanup="$outnames $cleanup"  #Make sure the lock file is last.

    transfer $read_cmd '$pnfsnames' '$LOCAL_OUTPUT_DIR' '$cleanup' "$use_options" "$section" READ

    test_diff '$filenames' '$outnames' '$cleanup' "$section"
    permissions_test '$filenames' '$outnames' '$cleanup' "$section"
    size_test '$filenames' '$outnames' '$cleanup' "$section"

    cleanup_files '$cleanup'
}

#Helper function for all of the dcache tests.
__dcache_read_write_test()
{
    print_test_name $section

    #Test the version of encp.
    has_cache_switch
    if [ $? -eq 0 ]; then
        echo "Encp does not have --get-cache switch.  Skipping test and continuing." 1>&2
	return
    fi

    #Snag a random file.
    filelist=$(get_file_list "$LOCAL_INPUT_DIR")
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
	return
    fi
    filename=$(pick_random_files 1 $filelist)
    basename=$(basename $filename)
    pnfsname=$(absfile $PNFS_OUTPUT_DIR $basename)
    cleanup="$pnfsname $(get_lock_file_name $filename)"

    #Create the output file, set the size and get the pnfs id.
    size=$(ls -l $filename | sed 's/ \{1,30\}/ /g' | cut -f 5 "-d ")
    if [ -n "$REMOTE_ENCP" ]; then
	$enstore_cmd pnfs_agent --touch "${pnfsname}"
	$enstore_cmd pnfs_agent --size "${pnfsname}" "${size}"
	pnfsid=$($enstore_cmd pnfs_agent --id "${pnfsname}")
    else
	make_file "${pnfsname}"
	if [ $? -ne 0 ]; then
	    echo "Failed to make file" 1>&2
	    echo 	make_file "${pnfsname}"  1>&2
	    exit 1
	fi
	$enstore_cmd sfs --size "${pnfsname}" "${size}"
	if [ $? -ne 0 ]; then
	    echo "Failed to set the size" 1>&2
	    exit 1
	fi
	pnfsid=$($enstore_cmd sfs --id "${pnfsname}")
	if [ $? -ne 0 -o -z "$pnfsid" ]; then
	    echo "Failed to get the id" 1>&2
	    echo "ENCP_OUTPUT $ENCP_OUTPUT" 1>&2
	    exit 1
	fi
    fi

    #Shorten some things for readability.
    options=`eval echo "$@"`
    put_id="--put-cache $pnfsid"
    get_id="--get-cache $pnfsid"

    #Do the write transfer and test for correctness.
    transfer $encp_cmd '$put_id' '$filename' '$cleanup' '$options' "$section" WRITE
    
    test_layer '$pnfsname' "$section"
    scan_test '$pnfsname' "$section"

    #Add the second direction.
    outname=$(absfile $LOCAL_OUTPUT_DIR $basename)
    cleanup="$outname $cleanup"  #Make sure the lock file is last.

    #Do the read transfer and test for correctness.
    transfer $encp_cmd '$get_id' '$outname' '$cleanup' '$options' "$section" READ

    test_diff '$filename' '$outname' '$cleanup' "$section"
    permissions_test '$filename' '$outname' '$cleanup' "$section"
    size_test '$filename' '$outname' '$cleanup' "$section"

    #Test the version of encp.
    is_admin_encp
    if [ $? -ne 0 ]; then
	#Only the admin version of encp has the --bfid switch.
        rm_file $outname

        #Do the read transfer and test by BFID instead of PNFSID.
	bfid=$($enstore_cmd sfs --bfid "${pnfsname}")
        get_bfid="--get-bfid $bfid"
        transfer $encp_cmd '$get_bfid' '$outname' '$cleanup' '$options' "$section" READ

        test_diff '$filename' '$outname' '$cleanup' "$section"
        permissions_test '$filename' '$outname' '$cleanup' "$section"
        size_test '$filename' '$outname' '$cleanup' "$section"
    fi
     
    cleanup_files '$cleanup'
}

__volume_read_test()
{
# $1 = encp/get command to use

    section="VOLUME READ"
    print_test_name $section

    #Test the version of encp.
    has_volume_switch
    if [ $? -eq 0 ]; then
        echo "Encp does not have --volume switch.  Skipping test and continuing." 1>&2
        return
    fi 

    encp="$1"

    #Snag a volume_read_test volume.
    tmp_volumes=$($enstore_cmd info --query "select label from volume where file_family = 'volume_read_test' and label not like '%.deleted' ;")
    volumes=$(echo "$tmp_volumes" | sed '1,2d') #Remove the header.
    if [ -z "$volumes" ]; then
	echo "No suitable volumes found.  Skipping test and continuing." 1>&2
    else
	#Pick a random volume.
	volume=$(pick_random_volumes 1 $volumes)

	outname=/dev/null

	transfer "$encp" '' '$outname' "" "--skip-deleted-files --volume $volume" "$section" READ
    fi
}

##############################################################################
# The functions defined here to the end of the file execute the actuall tests.
#
# First are the encp tests.
#
##############################################################################

single_read_test()
{
    section="SINGLE READ"
    #Run the basic read test.
    __read_test "$encp_cmd" 1 ""
}

single_read_write_test()
{
    section="SINGLE READ AND WRITE"
    #Use encp for read and write tests.  Copy 1 file.  No options.
    __read_write_test "$encp_cmd" "$encp_cmd" 1 ""
}

multiple_read_write_test()
{
    section="MULITPLE READ AND WRITE"
    # Use encp for read and write tests.
    __read_write_test "$encp_cmd" "$encp_cmd" 3
}

dcache_read_write_test()
{
    section="DCACHE READ AND WRITE"

    has_mount_point_switch
    if [ $? -eq 0 ]; then
	print_test_name $section
        echo "The 'enstore [sfs|pnfs_agent] --mount-point' command is not available.  Skipping test and continuing." 1>&2
	return
    fi

    pnfs_mount_point=$($enstore_cmd sfs --mount-point $PNFS_DIR)

    #Otherwise run the test.
    __dcache_read_write_test '--pnfs-mount "$pnfs_mount_point"'
}

dcache_shortcut_read_write_test()
{
    section="DCACHE SHORTCUT READ AND WRITE"

    has_mount_point_switch
    if [ $? -eq 0 ]; then
	print_test_name $section
        echo "The 'enstore [sfs|pnfs_agent] --mount-point' command is not available.  Skipping test and continuing." 1>&2
	return
    fi

    pnfs_mount_point=$($enstore_cmd sfs --mount-point $PNFS_DIR)

    #Otherwise run the test.
    __dcache_read_write_test '--shortcut --pnfs-mount "$pnfs_mount_point"'
}

dcache_override_path_read_write_test()
{
    section="DCACHE OVERRIDE PATH READ AND WRITE"
    #Use single quotes so that we can expand $pnfsname after we know it.
    __dcache_read_write_test '--shortcut --override-path "$pnfsname"'
}

dcache_dirpath_read_write_test()
{
    section="DCACHE DIRNAME READ AND WRITE"
    #Use single quotes so that we can expand $PNFS_DIR after we know it.
    __dcache_read_write_test '--pnfs-mount "$PNFS_DIR"'
}

dcache_dirpath_shortcut_read_write_test()
{
    section="DCACHE DIRNAME SHORTCUT READ AND WRITE"
    #Use single quotes so that we can expand $PNFS_DIR after we know it.
    __dcache_read_write_test '--shortcut --pnfs-mount "$PNFS_DIR"'
}

enstore_conf_read_write_test()
{
    section="ENSTORE.CONF READ AND WRITE"

    #Once the first test sets the contents of this file, any additional tests
    # should just use it.
    temp_config_file=/tmp/enstore.conf
    #We need each test instance to setup its own copy.
    temp_temp_config_file=${temp_config_file}.$$

    if [ ! -f "$temp_config_file" ]; then
        #Hack up the temporary enstore.conf file.
        if [ -f "$ENSTORE_CONF" ]; then
            #If we already have a valid $ENSTORE_CONF file, use it.
            cp "$ENSTORE_CONF" "$temp_temp_config_file"	
        elif [ -f "/etc/enstore.conf" ]; then
            cp /etc/enstore.conf "$temp_temp_config_file"
        else
            env | grep ENSTORE_CONFIG_HOST > "$temp_temp_config_file"
            env | grep ENSTORE_CONFIG_PORT >> "$temp_temp_config_file"
        fi

        #It is possible that the user has modified the environmental variables
        # from what is in the normal enstore.conf file.  Correct the temp copy.
	correct_config_file ENSTORE_CONFIG_HOST "$temp_temp_config_file" && \
	    correct_config_file ENSTORE_CONFIG_PORT "$temp_temp_config_file"
	if [ $? -ne 0 ]; then
	    print_test_name $section
	    echo "Failed to set $temp_config_file.  Skipping test and continuing." 1>&2
	    return
	fi

	mv "$temp_temp_config_file" "$temp_config_file"
	if [ $? -ne 0 ]; then
            echo "Failed to copy $temp_temp_config_file to $temp_config_file." \
		 "  Skipping test and continuing."
	    return
	fi
    fi

    #Override environment for this test.
    use_encp="env ENSTORE_CONFIG_HOST= ENSTORE_CONFIG_PORT= ENSTORE_CONF=$temp_config_file $encp_cmd"

    __read_write_test '$use_encp' '$use_encp' 1 ""
}	

single_threaded_read_write_test()
{
    section="SINGLE THREADED READ AND WRITE"
    #Transfer 1 file in threaded mode.
    __read_write_test "$encp_cmd" "$encp_cmd" 3 "--threaded"
}

multiple_threaded_read_write_test()
{
    section="MULITPLE THREADED READ AND WRITE"
    #Transfer 3 files in threaded mode.
    __read_write_test "$encp_cmd" "$encp_cmd" 3 "--threaded"
}

single_ecrc_read_write_test()
{
    section="SINGLE ECRC READ AND WRITE"
    #Read a file back off of disk with --ecrc.
    __read_write_test "$encp_cmd" "$encp_cmd" 1 "--ecrc"
}

single_relative_path_read_write_test()
{
    section="SINGLE RELATIVE PATH READ AND WRITE"
    print_test_name $section

    if [ -n "$REMOTE_ENCP" ]; then
	echo "Detected using pnfs_agent.  Skipping test and continuing." 1>&2
    else
	cwd=`pwd`

        #Snag a random file.
	filelist=`get_file_list "$LOCAL_INPUT_DIR"`
	filename=`pick_random_files 1 $filelist`
	basename=`basename $filename`
	pnfsname=`echo $basename`
	cleanup="$pnfsname `get_lock_file_name $filename`"

	cd_status=1
	cd_count=1
	while [ $cd_status -ne 0 -a $cd_count -lt 4 ]; do
	   cd ${PNFS_OUTPUT_DIR}/  #This can spuriously fail with Chimera.
	   cd_status=$?
	   cd_count=$((count + 1))
        done

	transfer $encp_cmd '$filename' '$pnfsname' '$cleanup' "" "$section" WRITE
	
	test_layer '$pnfsname' "$section"
	scan_test '$pnfsname' "$section"
	
        #Add the second direction.
	outname=`echo ${LOCAL_OUTPUT_DIR}/$basename`
	cleanup="$outname $cleanup"  #Make sure the lock file is last.

	transfer $encp_cmd '$pnfsname' '$outname' '$cleanup' "" "$section" READ

	test_diff '$filename' '$outname' '$cleanup' "$section"
	permissions_test '$filename' '$outname' '$cleanup' "$section"
	size_test '$filename' '$outname' '$cleanup' "$section"
	
	cleanup_files '$cleanup'
	
	cd_status=1
	cd_count=1
	while [ $cd_status -ne 0 -a $cd_count -lt 4 ]; do
	    cd $cwd
	    cd_status=$?
	    cd_count=$((count + 1))
        done
    fi
}

single_local_pnfs_path_read_test()
{
    section="SINGLE LOCAL PNFS PATH READ"
    print_test_name $section

    #Snag a random file.
    filelist=`get_pnfs_file_list "$PNFS_INPUT_DIR"`
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing."
    else
	filename=`pick_random_files 1 $filelist`
	basename=`basename $filename`
	#Insert the directory name "pnfs" into the local path.
	outdir=$LOCAL_OUTPUT_DIR/pnfs/
	outname=${outdir}/${basename}
	cleanup="$outname `get_lock_file_name $filename`"  #Make sure the lock file is last.

	#If this does not exist, create it.
	mkdir -p $outdir
	
	transfer $encp_cmd '$filename' '$outname' '$cleanup' "" "$section" READ

	cleanup_files '$cleanup'
    fi
}

single_no_brand_read_test()
{
    section="SINGLE NO BRAND READ"
    print_test_name $section

    #Snag the specific test file.
    filelist="$PNFS_INPUT_DIR/special_files/no_brand"
    if [ -z "$filelist" -o ! -f "$filelist" ]; then
	echo "Input file not found.  Skipping test and continuing." 1>&2
    elif [ `$enstore_cmd sfs --bfid $filelist | tr -d '[0-9]\n' | wc -c` -gt 0 ]; then
	#We should only get here if the bfid contains more than just
	# digits (and a newline).
	echo "$filelist bfid contains brand.  Skipping test and continuing." 1>&2
    else
	filename=`pick_random_files 1 $filelist`
	if [ -z "$filename" ]; then
	    echo "Input file not available.  Skipping test and continuing." 1>&2
	    return
	fi
	outname=/dev/null
	cleanup="$outname `get_lock_file_name $filename`"    #Make sure the lock file is last.

	transfer $encp_cmd '$filename' '$outname' '$cleanup' "" "$section" READ

	cleanup_files '$cleanup'
    fi
}

volume_read_test()
{
    section="VOLUME READ"
    #Use single quotes so that we can expand $PNFS_DIR after we know it.
    __volume_read_test "$encp_cmd"
}

single_fs_path_read_test()
{
    section="SINGLE FS PATH READ"
    print_test_name $section

    #Snag a random file.
    filelist=`get_pnfs_file_list "$PNFS_INPUT_DIR"`
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
    else
	filename=`pick_random_files 1 $filelist`
	#Turn this path into the dcache prefered /pnfs/fs/usr/... path.
	# Encp should be able to determine the /pnfs/... path.
	encp_filename=`echo $filename | cut -c1-6`fs/usr`echo $filename | cut -c6-`
	outname=/dev/null
	cleanup="$outname `get_lock_file_name $filename`"  #Make sure the lock file is last.

	transfer $encp_cmd '$encp_filename' '$outname' '$cleanup' "" "$section" READ

	cleanup_files '$cleanup'
    fi
}

data_access_layer_read_write_test()
{
    section="DATA ACCESS LAYER READ WRITE"
    print_test_name $section

    #Snag a random file.
    filelist=`get_file_list "$LOCAL_INPUT_DIR"`
    filename=`pick_random_files 1 $filelist`
    basename=`basename $filename`
    pnfsname=`echo ${PNFS_OUTPUT_DIR}/$basename`
    cleanup="$pnfsname `get_lock_file_name $filename`"
    encp="$encp_cmd --data-access-layer"

    transfer '$encp' '$filename' '$pnfsname' '$cleanup' "" "$section" WRITE

    test_layer '$pnfsname' "$section"
    data_access_layer_test '$filename' '$pnfsname' '$cleanup' "$section"
    scan_test '$pnfsname' "$section"
    
    #Add the second direction.
    outname=`echo ${LOCAL_OUTPUT_DIR}/$basename`
    cleanup="$outname $cleanup"  #Make sure the lock file is last.

    transfer '$encp' '$pnfsname' '$outname' '$cleanup' "" "$section" READ

    data_access_layer_test '$pnfsname' '$outname' '$cleanup' "$section"
    test_diff '$filename' '$outname' '$cleanup' "$section"
    permissions_test '$filename' '$outname' '$cleanup' "$section"
    size_test '$filename' '$outname' '$cleanup' "$section"

    cleanup_files '$cleanup'
}

multiple_copies_read_write_test()
{
    section="MULTIPLE COPIES READ WRITE"
    print_test_name $section

    #Test the version of encp.
    has_library_switch
    if [ $? -eq 0 ]; then
        echo "Encp does not have --library switch.  Skipping test and continuing." 1>&2
	return
    fi

    #Snag a random file.
    filelist=`get_file_list "$LOCAL_INPUT_DIR"`
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
    else
	filename=`pick_random_files 1 $filelist`
	basename=`basename $filename`
	pnfsname=`echo ${PNFS_OUTPUT_DIR}/$basename`
	cleanup="$pnfsname `get_lock_file_name $filename`"
	library=$($enstore_cmd sfs --tag library "${PNFS_OUTPUT_DIR}")
	encp="$encp_cmd --copies 1 --library $library,$library"
	
	#Write the original and one copy to tape.
	transfer '$encp' '$filename' '$pnfsname' '$cleanup' "" "$section" WRITE
	test_layer '$pnfsname' "$section"
	enstore_check_test '$pnfsname' '$cleanup' "$section"

	#Add the second direction.
	outname=`echo ${LOCAL_OUTPUT_DIR}/$basename`	
	cleanup="$outname $cleanup"  #Make sure the lock file is last.

	#Do the read transfer and test for correctness of the original.
	transfer $encp_cmd '$pnfsname' '$outname' '$cleanup' "" "$section" READ
	scan_test '$pnfsname' "$section"   #TO DO: scan copy bfid

	rm_file $outname

	#Now read back the copy via bfid.
	bfid=$($enstore_cmd sfs --bfid "$pnfsname")
	
	get_bfid="--get-bfid `$enstore_cmd file --find-copies $bfid`"
	transfer $encp_cmd '$get_bfid' '$outname' '$cleanup' "" "$section" READ

	rm_file $outname

	#Now read back the copy via copy number.
	transfer "$encp_cmd --copy 1" '$pnfsname' '$outname' '$cleanup' "" "$section" READ

        cleanup_files '$cleanup'
    fi
}

pnfs_agent_read_write_test()
{
    section="PNFS AGENT READ WRITE"
    print_test_name $section

    #Test the version of encp.
    is_admin_encp
    if [ $? -eq 0 ]; then
        echo "Encp is user version.  Skipping test and continuing." 1>&2
	return
    fi

    #This gets set to true if we temporarily enable $REMOTE_ENCP for encp
    # to use pnfs_agent.
    clear_remote_encp=0

    #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 [ -z "$REMOTE_ENCP" ]; then
	$try_enstore_cmd pnfs_agent --alive --timeout 3 --retries 3
	if [ $? -eq 0 ]; then
	    #We detected that the pnfs_agent is running, lets use it.
	    export REMOTE_ENCP=only_pnfs_agent
	    clear_remote_encp=1
	else
	    echo "pnfs_agent is not running.  Skipping test and continuing." 1>&2
	    return
	fi
    fi

    #Snag a random file.
    filelist=`get_file_list "$LOCAL_INPUT_DIR"`
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
    else
	filename=`pick_random_files 1 $filelist`
	basename=`basename $filename`
	pnfsname=`echo ${PNFS_AGENT_OUTPUT_DIR}/$basename`
	cleanup="$pnfsname `get_lock_file_name $filename`"
	encp="$encp_cmd"
	
	transfer "$encp" '$filename' '$pnfsname' '$cleanup' "" "$section" WRITE

	### These two tests need to be made pnfs_agent aware.
	test_layer '$pnfsname' "$section"
	enstore_check_test '$pnfsname' '$cleanup' "$section"

	#Add the second direction.
	outname=`echo ${LOCAL_OUTPUT_DIR}/$basename`
	cleanup="$outname $cleanup"  #Make sure the lock file is last.

	transfer "$encp" '$pnfsname' '$outname' '$cleanup' "" "$section" READ
    fi
    
    cleanup_files '$cleanup'
    if [ $clear_remote_encp -eq 1 ]; then
        unset REMOTE_ENCP
    fi
}

setuid_read_write_test()
{
#Having a suitable setuid executable for this test is a security issue.
    return  #This test is disabled.

    section="SETUID READ AND WRITE"
    print_test_name $section
    
    which setuid > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	echo "Unable to find setuid.  Skipping test and continuing." 1>&2
	return
    fi

    #Snag a random file.
    filelist=`get_file_list "$LOCAL_INPUT_DIR"`
    for file in $filelist; do      #remove non-group permission files.
        if [ `ls -l $file | cut -c5` = "r" ] ; then
	    filelist2=`echo $filelist2 $file`
	fi
    done
    RANDOM=`date +s`
    filename=`pick_random_files 1 $filelist2`
    basename=`basename $filename`
    pnfsname=`absfile $PNFS_OUTPUT_DIR $filename`
    cleanup="$pnfsname `get_lock_file_name $filename`"
    
    transfer "setuid $encp_cmd" '$filename' '$pnfsname' '$cleanup' "" "$section" WRITE

    #Test if an error occured or if an error is what we expect.
    setuid test_layer '$pnfsname' "$section"
    rtn=$?
    #If we have read permissions and an error did occure.
    test -r $pnfsname -a $rtn -ne 0
    val1=$?
    #If an error did not occur but we do not have read permission.
    test ! -r $pnfsname -a $rtn -eq 0
    val2=$?
    if [ $val1 -o $val2 ]; then
	if [ $rtn -eq 1 ]; then
	    echo "Read permissions exist, yet pnfs layer read failure." 1>&2
	    setuid rm_file $outname
	    setuid rm_file $pnfsname
	    exit
	fi
    fi

    #Add the second direction.
    outname=`absfile $LOCAL_OUTPUT_DIR $filename`
    cleanup="$outname $cleanup"  #Make sure the lock file is last.

    transfer "setuid $encp_cmd" '$pnfsname' '$outname' '$cleanup' "" "$section" READ

    test_diff '$filename' '$outname' '$cleanup' "$section"
    permissions_test '$filename' '$outname' '$cleanup' "$section"
    size_test '$filename' '$outname' '$cleanup' "$section"

    setuid cleanup_files '$cleanup' 
}

pipe_write_test()
{
#The library mananager expects the encp ticket value, size_bytes, to 
# contain a number.  This is not possible for pipe writes and thus
# the test will always fail.  Bugzilla number ???
    return  #This test is disabled.

    section="PIPE WRITE"
    print_test_name $section

    #Snag a random file.
    filelist=`get_file_list "$LOCAL_INPUT_DIR"`
    if [ -z "$filelist" ]; then
	echo "Input directory empty.  Skipping test and continuing." 1>&2
    else
	filename=`pick_random_files 1 $filelist`
	basename=`basename $filename`
	pnfsname=`echo ${PNFS_OUTPUT_DIR}/$basename`
	cleanup="$pnfsname `get_lock_file_name $filename`"
	encp="echo tttt | $encp_cmd"
	
        #First test that encp ingnores the standard in pipe when simulating
        # a cron environment.
        # (Note that $encp is in single quotes to delay the shells expansion
        # to the eval in transfer().)
	transfer '$encp' "$filename" "$pnfsname" "$cleanup" "" "$section" WRITE

	test_layer "$pnfsname" "$section"
	enstore_check_test '$pnfsname' '$cleanup' "$section"

	#Add the second direction.
	outname=`echo ${LOCAL_OUTPUT_DIR}/$basename`
	cleanup="$outname $cleanup"  #Make sure the lock file is last.

	transfer "$encp_cmd" "$pnfsname" '$outname' '$cleanup' "" "$section" READ

	cleanup_files '$cleanup'
	cleanup="$pnfsname `get_lock_file_name $filename`"

	#Second test that encp reads from standard in when there is not
	# an input file on the command line and standard in is a pipe.
        # (Note that $encp is in single quotes to delay the shells expansion
        # to the eval in transfer().)
	transfer '$encp' "" "$pnfsname" "$cleanup" "" "$section" WRITE

	test_layer '$pnfsname' "$section"
	enstore_check_test '$pnfsname' '$cleanup' "$section"
	
	#Add the second direction.
	outname=`echo ${LOCAL_OUTPUT_DIR}/$basename`
	cleanup="$outname $cleanup"  #Make sure the lock file is last.

	transfer "$encp_cmd" "$pnfsname" '$outname' '$cleanup' "" "$section" READ

        cleanup_files '$cleanup'
    fi
}

source_file_does_not_exist_write_test()
{
    section="SOURCE FILE DOES NOT EXIST WRITE"
    print_test_name $section

    #Make up a bogus source file.
    filename=/tmp/i_dont_exist/i_dont_exist
    pnfsname=${PNFS_OUTPUT_DIR}/i_dont_exist
    cleanup="$pnfsname `get_lock_file_name $filename`"  #Make sure the lock file is last.

    #Test if encp returns an error.
    transfer "$encp_cmd" "$filename" "$pnfsname" "$cleanup" "" "$section" WRITE 1
    
    cleanup_files '$cleanup'
}

library_does_not_exist_write_test()
{
    section="LIBRARY DOES NOT EXIST WRITE"

    #Test the version of encp.
    has_library_switch
    if [ $? -eq 0 ]; then
        echo "Encp does not have --library switch.  Skipping test and continuing." 1>&2
	return
    fi

    #This test is expected to fail.
    __write_test "$encp_cmd" 1 "--library this_library_does_not_exist" 1
}

too_many_resubmits_write_test()
{
    section="TOO MANY RESUBMITS WRITE"
    print_test_name $section

    #Test the version of encp.
    has_max_resubmits_switch
    if [ $? -eq 0 ]; then
        echo "Encp does not have --max-resubmits switch.  Skipping test and continuing." 1>&2
	return
    fi

    #This test is expected to fail.
    __write_test "$encp_cmd" 1 "--resubmit-timeout 0 --max-resubmit 0" 1
}

#This test requires zero PNFS/Chimera mount points to be available.  It is
# also the only test that does not require $PNFS_DIR or -p to be used.
skip_sfs_read_test()
{
    section="SKIP SFS READ"
    print_test_name $section

    #Verify that no PNFS or Chimera mount points are available.
    sfs_mounts=$(mount | grep -E "pnfs|chimera" | awk '{print $3}')
    if [ -n "$sfs_mounts" ]; then
	#Since this test needs to be enabled by the user, give error.
	echo "Storage filesystem mounts exist.  Aborting." 1>&2
	echo $sfs_mounts 1>&2
	exit 1
    fi
    
    #Snag a volume_read_test volume.
    tmp_volumes=$($enstore_cmd info --query "select label from volume where file_family = 'volume_read_test' and label not like '%.deleted' ;")
    volumes=$(echo "$tmp_volumes" | sed '1,2d') #Remove the header.
    if [ -z "$volumes" ]; then
	echo "No suitable volumes found.  Skipping test and continuing." 1>&2
    else
	#Pick a random volume.
	volume=$(pick_random_volumes 1 $volumes)
	#Get the list of active bfids.
	bfid_list=$($enstore_cmd info --list $volume)	
	active_bfids=$(echo "$bfid_list" | grep active | awk '{print $2}')
	if [ -z "$active_bfids" ]; then
            echo "No suitable bfids found on $volume.  Skipping test and continuing." 1>&2
	    return
	fi
	#Pick a random active bfid.
	bfid=$(pick_random_bfids 1 $active_bfids)

	outname=/dev/null
	cleanup="$outname"

	#Do the read transfer and test by BFID.
	get_bfid="--get-bfid $bfid --skip-pnfs"
	transfer $encp_cmd '$get_bfid' '$outname' '$cleanup' '$options' "$section" READ
    
    fi

    cleanup_files '$cleanup'
    
}

##############################################################################
#
# Next are the other tests.
#
##############################################################################

single_assert_test()
{
    section="SINGLE ASSERT"
    print_test_name $section

    if [ -z "$volume_assert_cmd" ]; then
        echo "Unable to find volume_assert.  Skipping test and continuing." 1>&2
	return
    fi

    #Snag a volume_read_test volume.
    volumes=$($enstore_cmd info --query "select label from volume where file_family = 'volume_read_test' and label not like '%.deleted' ;" | sed '1,2d')
    if [ -z "$volumes" ]; then
	echo "No suitable volumes found.  Skipping test and continuing." 1>&2
    else
	#Pick a random volume.
	volume=$(pick_random_volumes 1 $volumes)
	if [ -z "$volume" ]; then
            echo "No suitable volume found." 1>&2
            return
        fi
	media_type=$($enstore_cmd info --gvol $volume | grep media_type | awk '{print $2}' | tr -d "',")
        if [ -z $media_type ]; then
            echo "No media type found." 1>&2
            return
        elif [ $media_type = "disk" -o $media_type = "null" ]; then
            # ees stands for Expected Exit Status.
            ees=1  #Disk and null volumes are not assertable.
        else
            ees=0  #Tape volumes are assertable.
        fi

	transfer '$volume_assert_cmd' '--volume $volume' '' '' '' "SINGLE ASSERT" READ $ees
    fi
}

ensync_test()
{
    section="ENSYNC"
    print_test_name $section

    if [ -z "$ensync_cmd" ]; then
        echo "Unable to find ensyc.  Skipping test and continuing." 1>&2
	return
    fi

    #Snag a directory, not a file or multiple files.
    input_dir=`pick_random_files 1 "$ENSYNC_INPUT_DIR"`  #lock it from others
    output_dir=$ENSYNC_OUTPUT_DIR
    #Remember to cleanup the lock for the directory, not the files.  It is
    # important to note that the lock file 
    cleanup=`get_lock_file_name $input_dir`  #Make sure the lock file is last.

    if [ ! -d $input_dir ]; then
	echo "Input directory does not exist.  Skipping test and continuing." 1>&2
    elif [ ! -d $output_dir ]; then
	echo "Output directory does not exist.  Skipping test and continuing." 1>&2
    else
	transfer '$ensync_cmd' '$input_dir' '$output_dir' '$cleanup' '' '$section' WRITE 
    fi

    cleanup_dir '$output_dir'  #Remove the test files before the lock file.
    cleanup_files '$cleanup'
}


get_put_test()
{
#The get executable has bugzilla ticket #459 open.  This bug prevents a get
# command from having its requests given to movers if the tape is already
# mounted.
#
#The put executable has never worked.  Bugzilla #525.
    return  #This test is disabled.

    section="GET AND PUT"

    if [ -z "$get_cmd" ]; then
        print_test_name $section
        echo "Unable to find get.  Skipping test and continuing." 1>&2
	return
    fi
    if [ -z "$put_cmd" ]; then
        print_test_name $section
        echo "Unable to find put.  Skipping test and continuing." 1>&2
	return
    fi

    #Use get and put for read and write tests.
    __read_write_test "$get_cmd" "$put_cmd" 3 
}

get_volume_test()
{
#The get executable has bugzilla ticket #459 open.  This bug prevents a get
# command from having its requests given to movers if the tape is already
# mounted.
    return  #This test is disabled.

    section="GET VOLUME"

    if [ -z "$get_cmd" ]; then
        print_test_name $section
        echo "Unable to find get.  Skipping test and continuing." 1>&2
	return
    fi

    __volume_read_test "$get_cmd"
}

enmv_test()
{
    section="ENMV"

    if [ -z "$enmv_cmd" ]; then
        print_test_name $section
        echo "Unable to find enmv.  Skipping test and continuing." 1>&2
	return
    fi
    
    #Snag a random file.
    filelist=`get_pnfs_file_list "$PNFS_INPUT_DIR"`
    if [ -z "$filelist" ]; then
        print_test_name $section
	echo "Input directory empty.  Skipping test and continuing." 1>&2
	return
    else
	pnfsname=`pick_random_files 1 $filelist`

	#Rename a file to itself.  Enmv supports it.  This usage also has
        # some side-effects, like updating the path in the Enstore DB.
	transfer '$enmv_cmd' "$pnfsname" "$pnfsname" "" "" "$section" MOVE

	scan_test "$pnfsname" "$section"

        #Note: Since we are moving the file to itself, only remove the
	# lock file.
        cleanup_files `get_lock_file_name $pnfsname`
    fi
}
