#!/usr/bin/env bash

# This script checks sufficiency of installed Qt5 system for the CoCoA5 GUI.
# Exit code is 0 iff sufficient, o/w non-zero.

# This script expects no arguments.

SCRIPT_NAME="[[$(basename "$0")]]"
SCRIPT_DIR="$(dirname "$0")"

if [ $# -ne 0 ]; then
    echo "ERROR: expected no args   $SCRIPT_NAME" > /dev/stderr
    exit 1
fi

# Create tmp directory, put test prog in it, compile and run.
umask 22
# shellcheck source=shell-fns.sh
. "$SCRIPT_DIR/shell-fns.sh"
TMP_DIR="$(mktempdir qt5-check)"

pushd "$TMP_DIR" > /dev/null || exit 255

# Check for qmake
echo "qmake -v" > LogFile
if ! qmake -v >> LogFile 2>&1; then
    # Deliberately leave $TMP_DIR to assist debugging.
    echo "ERROR: qmake does not work   $SCRIPT_NAME" > /dev/stderr
    exit 2
fi

# Create profile file for qmake
cat > qt5-check.pro <<EOF
QMAKE_MAKEFILE = qt5-check-makefile

TEMPLATE = app
TARGET = qt5-check
QT += xml webkitwidgets printsupport # crucial line with dependencies
SOURCES += qt5-check.cpp
EOF

# Create C++ file
cat > qt5-check.cpp <<EOF
#include <iostream>
#include <QtWidgets/QApplication> // a header file necessary for QCodeEdit

int main() {
    std::cout << "Qt5 version " << qVersion() << " found" << std::endl;
    return 0;
}
EOF

# Set qmake flag for macOS (see src/CoCoA-5/make-c5makefile.sh
#                           and src/CoCoA-5/make-qcodeeditmakefile.sh)
if [ "$(uname)" = "Darwin" ]; then
    DARWIN_OPTS="-spec macx-g++"
fi

# Use qmake to create makefile
echo "qmake $DARWIN_OPTS qt5-check.pro" > LogFile
if ! qmake $DARWIN_OPTS qt5-check.pro >> LogFile 2>&1; then
    # Deliberately leave $TMP_DIR to assist debugging.
    echo "ERROR: qmake exited abnormally --> see LogFile.   $SCRIPT_NAME" \
    > /dev/stderr
    exit 3
fi

# Use make to compile cpp file
echo "make --file=qt5-check-makefile" > LogFile
if ! make --file=qt5-check-makefile >> LogFile 2>&1; then
    # Deliberately leave $TMP_DIR to assist debugging.
    echo "ERROR: make exited abnormally --> see LogFile.   $SCRIPT_NAME" \
    > /dev/stderr
    exit 4
fi

# Run Qt5 program
echo "./qt5-check" > LogFile
if ! ./qt5-check >> LogFile 2>&1; then
    # Deliberately leave $TMP_DIR to assist debugging.
    echo "ERROR: qt5-check exited abnormally --> see LogFile.   $SCRIPT_NAME" \
     > /dev/stderr
    exit 5
fi

# Clean up $TMP_DIR
popd > /dev/null || exit 255
rm -rf "$TMP_DIR"

exit 0
