#!/bin/sh
# Run all of the IPC tests in one script. This is needed because
# make check could run with -j and the start and resource 'tests'
# need to run first and last respectively.

# Clean-up params
SOCKS_PER_PROCESS=3
EXPECTED_DLOCK=6
EXPECTED_LEFTOVER=2

tidy_qb_dirs()
{
    for dd in "$@"; do
	rm $dd
	rmdir $(dirname $dd) 2> /dev/null
    done
}

run_shm_ipcs()
{
    echo "======================= Running SHM IPC tests ======================="
    ./ipc.test
}

generate_sockname()
{
    #
    # Generate a unique(ish) name for the IPCs we will use in the tests and
    # save it in a file for all of the tests to use. This way we know for sure
    # which sockets are our and which we can ignore.
    # The test programs all add "qb-test-<name>-" to the front of this.
    #
    NAME="$$-$(date +%s)"
    printf "$NAME" > ipc-test-name
    if [ ! -d $SOCKETDIR ]
    then
	mkdir -p $SOCKETDIR
    fi
}

run_sock_ipcs()
{
    # filesystem socket IPC test
    if [ "$(uname -s)" = "Linux" ] && [ "`id -u`" = "0" ]
    then
	echo "======================= Running socket IPC tests ======================="

	./ipc_sock.test
	RES=$?
	if [ "$RES" = "0" ]
	then
	    EXPECTED_DLOCK=12
	    EXPECTED_LEFTOVER=4
	fi
    fi
    return $RES
}

generate_sockname

# Normal IPC test
run_shm_ipcs
RESULT=$?

# Socket IPC test
run_sock_ipcs
# Don't override previous failure status
if [ $? != 0 ]
then
    RESULT=$?
fi

# Tidy up and check leftovers
IPC_NAME=$(cat ipc-test-name 2>/dev/null)
for d in /dev/shm /var/run $SOCKETDIR; do

	# Tidy up the deadlock checker sockets first
	dlocks=$(find $d -name "qb-*-test_*dlock*${IPC_NAME}*" -size +0c 2>/dev/null)
	if [ "$(echo $dlocks|wc -w)" -eq $(($SOCKS_PER_PROCESS * $EXPECTED_DLOCK)) ]; then
	        tidy_qb_dirs $dlocks
	        rm $dlocks
	elif [ -n "${dlocks}" ]; then
		echo
		echo "Error: dlock shared memory segments not closed/unlinked"
		echo
		RETURN=1
	fi

	# Now look for other expected leftovers
	leftovers=$(find $d -name "qb-*-test_*${IPC_NAME}*" -size +0c 2>/dev/null | wc -l)
	if [ "${leftovers}" -gt 0 ]; then
		echo
		echo "Error: shared memory segments not closed/unlinked"
		echo
		RETURN=1
	fi
	leftovers="$(find $d -name "qb-*-test_*${IPC_NAME}*" -size 0c 2>/dev/null)"
	if [ "$(printf '%s\n' "${leftovers}" | wc -l)" -eq $(($SOCKS_PER_PROCESS * $EXPECTED_LEFTOVER)) ]; then
		echo
		echo "There were some empty leftovers (expected), removing them"
		echo "${leftovers}"
		echo
		tidy_qb_dirs $leftovers
	elif [ -n "${leftovers}" ]; then
		echo
		echo "Error: unexpected number of empty leftovers"
		echo "${leftovers}"
		echo
		RETURN=1
	fi
done

# Clean up empty /dev/shm directories left over by some tests
DIRS=$(grep "Free'ing ringbuffer" all_ipcs.log | cut -f4 -d ' '|cut -f-4 -d'/'|sort|uniq)
for i in $DIRS
do
    rmdir $i 2>/dev/null
done


ps aux | grep -v grep | grep -E 'lt-.*\.test'
if [ $? -eq 0 ]; then
	echo "test program frozen"
	RETURN=1
fi

exit $RETURN
