#!/bin/sh

PARAVIEW_COMMAND="@CMAKE_INSTALL_PREFIX@/bin/paraview"
PARAVIEW_SOURCE_DIR="@PARAVIEW_SOURCE_DIR@"
PARAVIEW_BINARY_DIR="@PARAVIEW_BINARY_DIR@"
CMAKE_INSTALL_PREFIX="@CMAKE_INSTALL_PREFIX@"
CMAKE_BUILD_TOOL="@CMAKE_BUILD_TOOL@"
PARAVIEW_VERSION="@PARAVIEW_VERSION_MAJOR@.@PARAVIEW_VERSION_MINOR@"

trap cleanup 1 2 3 6

cleanup()
{
    (
        cd "${PARAVIEW_BINARY_DIR}"
        if [ -d "bin-TestInstallTemp" ]; then
            mv "bin-TestInstallTemp" "bin"
        fi
    )
    exit 1
}

install()
{
    echo "Erasing ${CMAKE_INSTALL_PREFIX}" &&
    ([ ! -d "${CMAKE_INSTALL_PREFIX}" ] || rm -rf "${CMAKE_INSTALL_PREFIX}") &&
    mkdir -p "${CMAKE_INSTALL_PREFIX}" &&
    echo "Running make install" &&
    (
        cd "${PARAVIEW_BINARY_DIR}" &&
        "${CMAKE_BUILD_TOOL}" install
    )
}

run_test()
{
    (
        cd "${PARAVIEW_BINARY_DIR}"
        mv "bin" "bin-TestInstallTemp"
    )
    echo "Running ParaView"
    (
        cd "${CMAKE_INSTALL_PREFIX}"
        export LD_LIBRARY_PATH="${CMAKE_INSTALL_PREFIX}/lib/paraview-${PARAVIEW_VERSION}"
        "${PARAVIEW_COMMAND}" --disable-registry \
            "${PARAVIEW_SOURCE_DIR}/ParaView/Testing/Tcl/Delete.pvs" \
            -D "${PARAVIEW_SOURCE_DIR}/Data" \
            -C "${PARAVIEW_SOURCE_DIR}/Widgets/Testing/Tcl/CompareImages.tcl" \
            -V "${PARAVIEW_SOURCE_DIR}/Data/Baseline/Delete.png"
    )
    result="$?"
    (
        cd "${PARAVIEW_BINARY_DIR}"
        mv "bin-TestInstallTemp" "bin"
    )
    return $result
}

install && run_test
