#!/bin/sh
# Testing the installation: the version, paths and number of extensions should be correct
# This test entirely depends on the CamitK version (version string, number of extensions...)
# (see the expectedConfigOutput)
# 
# TODO: add complete library tests using cepgenerator
set -e
EXPECTED_CONFIG_OUTPUT=$(mktemp)
CONFIG_OUTPUT=$(mktemp)
DIFF_OUTPUT=$(mktemp)

# Clean up temporary files
cleanExit () {
	echo "Exiting (cleaning up)"
	rm -f $EXPECTED_CONFIG_OUTPUT $CONFIG_OUTPUT $DIFF_OUTPUT
	# exit with the given status
	exit $1
}

# depending on the CamiTK version, the output is different
expectedConfigOutput () {

  if [ "$1" = "3.3.2" ]; then
		cat <<EOF > $EXPECTED_CONFIG_OUTPUT
CamiTK 3.3.2
- CamiTK version......................... CamiTK 3.3.2
- CamiTK Short Version................... camitk-3.3
- CamiTK SO NAME......................... 3
- CamiTK Global Installation Directory... /usr
- Component Extension Directories........ /usr/lib/camitk-3.3/components
- Action Extension Directories........... /usr/lib/camitk-3.3/actions
- Number of Component Extensions......... 12
- Number of Action Extensions............ 71
EOF
	fi

	if [ "$1" = "3.2.2" ]; then
		cat <<EOF > $EXPECTED_CONFIG_OUTPUT
- CamiTK version......................... CamiTK 3.2.2
- CamiTK Short Version................... camitk-3.2
- CamiTK SO NAME......................... 3
- CamiTK Global Installation Directory... /usr
- Component Extension Directories........ /usr/lib/camitk-3.2/components
- Action Extension Directories........... /usr/lib/camitk-3.2/actions
- Number of Component Extensions......... 10
- Number of Action Extensions............ 65
- Registered components (G=Global, L=Local, W=Working, U=User):
EOF
	fi
}

# if a problem occurs, call the clean method
trap cleanExit INT QUIT ABRT TERM PIPE

# First determine CamiTK version
CAMITK_VERSION=$(xvfb-run --auto-servernum --server-num=1 camitk-config --completeVersion | cut -f2 -d" ")
echo "Detected CamiTK version is $CAMITK_VERSION"

# build the expected output string
expectedConfigOutput $CAMITK_VERSION

# run the config diagnosis (skipping the user/path dependent part using sed)
# TODO: update the camitk-config code so that extensions are always listed in the same order
xvfb-run --auto-servernum --server-num=1 camitk-config --config | sed -n "1,5p; 9,12p" > $CONFIG_OUTPUT

# compare output to expected output
echo "Checking configuration..."

# || true is to ignore the output of the diff (we need to know more, the set -e would stop the execution of the script here
# if || true was not added and there was a difference between the two files
diff --context=1 --suppress-common-lines "$CONFIG_OUTPUT" "$EXPECTED_CONFIG_OUTPUT" > $DIFF_OUTPUT || true
if [ -s $DIFF_OUTPUT ]; then
    echo "CamiTK $CAMITK_VERSION configuration: Failed"
    cat $DIFF_OUTPUT
    false
else
    echo "CamiTK $CAMITK_VERSION configuration: OK"
    true
fi

