#!/bin/sh
# Detect It Easy - configure wrapper around CMake.
# Usage: ./configure [--prefix=PREFIX] [--qt=QT_PREFIX_PATH]
# Afterwards run: make && make install
#
# Binaries are placed in build/release/ (die, diec, diel) so the
# install.sh / create_appimage.sh scripts find them at the usual paths.

PREFIX=/usr
QT_PREFIX_PATH=
BUILD_DIR=build

for arg in "$@"; do
    case "$arg" in
        --prefix=*) PREFIX="${arg#--prefix=}" ;;
        --qt=*)     QT_PREFIX_PATH="${arg#--qt=}" ;;
        -h|--help)
            echo "Usage: ./configure [--prefix=PREFIX] [--qt=QT_PREFIX_PATH]"
            echo "Configures the CMake build. Afterwards run: make && make install"
            exit 0
            ;;
        *)
            echo "configure: ignoring unknown option: $arg" ;;
    esac
done

set -- -S . -B "$BUILD_DIR" \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX="$PREFIX" \
    -DCMAKE_RUNTIME_OUTPUT_DIRECTORY="$(pwd)/build/release"
if [ -n "$QT_PREFIX_PATH" ]; then
    set -- "$@" -DCMAKE_PREFIX_PATH="$QT_PREFIX_PATH"
fi

cmake "$@" || exit 1

# Bare "-j" means unlimited parallelism, which spawns one compiler per ready
# target and exhausts memory on CI runners. Bake in a concrete job count.
NPROC=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)

cat > Makefile <<EOF
# Generated by ./configure - delegates to the CMake build.
all:
	cmake --build $BUILD_DIR -j$NPROC

install:
	bash -x install.sh $PREFIX

clean:
	rm -rf $BUILD_DIR

.PHONY: all install clean
EOF

echo "The configure finished. Please type \"make\" to compile the project."
