#!/bin/sh
set -e

BUILD_TYPE="Release"
PREFIX="/usr"
WITH_SYNCTEX="on"
WITH_LUA="on"

print_help() {
    cat <<EOF
    Usage: ./configure [OPTIONS]

    Options:
    --prefix PATH           Set the installation prefix [default: /usr]
    --build-type TYPE       Set the CMake build type [default: Release]
    Valid values: Debug, Release, RelWithDebInfo
    --with-synctex          Enable SyncTeX support (default: true)
    --without-synctex       Disable SyncTeX support
    --with-lua              Enable Lua scripting support (requires Lua) (default: false)
    --without-lua           Disable Lua scripting support
    -h, --help              Show this help message and exit

    Examples:
    ./configure
    ./configure --prefix /usr/local --build-type Release
EOF
}

# Check for the arguments
while [ "$#" -gt 0 ]; do
    case "$1" in
        --build-type)
            BUILD_TYPE="$2"
            shift 2
            ;;
        --prefix)
            PREFIX="$2"
            shift 2
            ;;
        --with-synctex)
            WITH_SYNCTEX="on"
            shift 1
            ;;
        --without-synctex)
            WITH_SYNCTEX="off"
            shift 1
            ;;
        --with-lua)
            WITH_LUA="on"
            shift 1
            ;;
        --without-lua)
            WITH_LUA="off"
            shift 1
            ;;
        -h|--help)
            print_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Run './configure --help' for usage."
            exit 1
            ;;
    esac
done

# Check if thirdparty mupdf directory exists and is not empty
if [ ! -d "thirdparty/mupdf" ] || [ -z "$(ls -A "thirdparty/mupdf")" ]; then
    echo "Error: The directory 'thirdparty/mupdf' does not exist or is empty."
    git submodule update --init --recursive
fi

if [ ! -d "thirdparty/synctex" ] || [ -z "$(ls -A "thirdparty/synctex")" ]; then
    echo "Error: The directory 'thirdparty/synctex' does not exist or is empty."
    git submodule update --init --recursive
fi

# Create the build directory if it doesn't exist
mkdir -p build

# If `ninja` is available, use it as the generator for CMake
if command -v ninja > /dev/null 2>&1; then
    export CMAKE_GENERATOR="Ninja"
fi

# Run cmake with the specified options
cmake -S . -B build \
    -DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
    -DCMAKE_INSTALL_PREFIX="$PREFIX" \
    -DWITH_SYNCTEX="$WITH_SYNCTEX" \
    -DWITH_LUA="$WITH_LUA"

cmake --build build

# vim:ft=bash
