#!/bin/bash

set -euo pipefail
source $(dirname $0)/var.sh

LIB_PATH=third_party/leptonica
CXXFLAGS="-I$INCLUDE_DIR $OPTIM_FLAGS -DMINIMUM_SEVERITY=4"
CM_FLAGS=(
  -DBUILD_SHARED_LIBS=OFF
  -DCMAKE_INSTALL_PREFIX=$BUILD_DIR
  -DCMAKE_PREFIX_PATH=$BUILD_DIR
  -DGIF_LIBRARY=$LIB_DIR/libgif.a
  -DGIF_INCLUDE_DIR=$INCLUDE_DIR
  -DZLIB_LIBRARY=$LIB_DIR/libz.a
  -DZLIB_INCLUDE_DIR=$INCLUDE_DIR
  -DPNG_LIBRARY=$LIB_DIR/libpng.a
  -DPNG_PNG_INCLUDE_DIR=$INCLUDE_DIR
  -DJPEG_LIBRARY=$LIB_DIR/libjpeg.a
  -DJPEG_INCLUDE_DIR=$INCLUDE_DIR
  -DTIFF_LIBRARY=$LIB_DIR/libtiff.a
  -DTIFF_INCLUDE_DIR=$INCLUDE_DIR
  -DWEBP_LIBRARY=$LIB_DIR/libwebp.a
  -DWEBP_INCLUDE_DIR=$INCLUDE_DIR
  -DWEBPMUX_INCLUDE_DIR=$INCLUDE_DIR
  -DHAVE_LIBJP2K=0
)

if [ $BUILD_WASM = 1 ]; then
  CM_FLAGS+=(-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_FILE)
fi

echo "CM_FLAGS=${CM_FLAGS[@]}"

cd $LIB_PATH
if [ $BUILD_CLEAN = 1 ]
then
  rm -rf build
fi
mkdir -p build
cd build
$CMAKE_CMD .. -DCMAKE_C_FLAGS="$CXXFLAGS" ${CM_FLAGS[@]}
$MAKE_CMD install -j$PROC
cd $ROOT_DIR
