#!/bin/sh

CMAKE_COMMAND="@CMAKE_COMMAND@"
VTK_SOURCE_DIR="@VTK_SOURCE_DIR@"
VTK_BINARY_DIR="@VTK_BINARY_DIR@"
CMAKE_INSTALL_PREFIX="@CMAKE_INSTALL_PREFIX@"
CMAKE_MAKE_PROGRAM="@CMAKE_MAKE_PROGRAM@"

SOURCE_DIR="${VTK_SOURCE_DIR}/Common/Testing/Install"
BINARY_DIR="${VTK_BINARY_DIR}/Common/Testing/Install"

trap cleanup 1 2 3 6

cleanup()
{
    (
        cd "${VTK_BINARY_DIR}"
        if [ -d "bin-InstallTestTemp" ]; then
            mv "bin-InstallTestTemp" "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 "${VTK_BINARY_DIR}" &&
        "${CMAKE_MAKE_PROGRAM}" install
    )
}

setup()
{
    echo "Entering ${BINARY_DIR}" &&
    cd "${BINARY_DIR}"
}

write_cache()
{
    install || return 1
    setup || return 1
    echo "Writing CMakeCache.txt"
    (
        cat > CMakeCache.txt <<EOF
VTK_DIR:FILEPATH=${CMAKE_INSTALL_PREFIX}/lib/vtk
EOF
    )
}

run_cmake()
{
    write_cache || return 1
    echo "Running CMake"
    "${CMAKE_COMMAND}" "${SOURCE_DIR}"
}

run_make()
{
    run_cmake || return 1
    echo "Running ${CMAKE_MAKE_PROGRAM}"
    "${CMAKE_MAKE_PROGRAM}"
}

run_test()
{
    (
        cd "${VTK_BINARY_DIR}"
        mv "bin" "bin-InstallTestTemp"
    )
    echo "Running ${BINARY_DIR}/vit"
    (
    "${BINARY_DIR}/vit"
    )
    result="$?"
    (
        cd "${VTK_BINARY_DIR}"
        mv "bin-InstallTestTemp" "bin"
    )
    return $result
}

run_make && run_test
