#!/usr/bin/env bash
#
# Build the lz4_nif shared library.
#
# Honors:
# ERTS_INCLUDE_DIR : path to erl_nif.h (default: derived from `erl`).
# CC : compiler (default: cc).
# CFLAGS : extra compile flags appended after defaults.
# LZ4_NIF_NO_NATIVE : if set, skip -march=native (use for portable builds).
#
# The ERTS include dir is resolved via
# erl -noshell -eval '...' -s init stop
# with **the correct option order** -- `-eval` before `-s init stop` -- so it
# runs cleanly on OTP 27+. (The reverse order, which granderl 0.1.5 used,
# silently terminates the node before -eval runs and leaves the var empty.)
set -eu
cd "$(dirname "$0")/.."
if [ -z "${ERTS_INCLUDE_DIR:-}" ]; then
ERTS_INCLUDE_DIR=$(erl -noshell \
-eval 'io:format("~s/erts-~s/include/", [code:root_dir(), erlang:system_info(version)]).' \
-s init stop)
fi
CC=${CC:-cc}
TARGET=priv/lz4_nif.so
SRCS="c_src/lz4_nif.c c_src/lz4/lz4.c"
BASE_CFLAGS="-fPIC -O3 -std=gnu11 -Wall -Wextra -Wno-unused-parameter"
if [ -z "${LZ4_NIF_NO_NATIVE:-}" ]; then
BASE_CFLAGS="$BASE_CFLAGS -march=native -mtune=native"
fi
LDFLAGS="-shared"
if [ "$(uname -s)" = "Darwin" ]; then
LDFLAGS="$LDFLAGS -undefined dynamic_lookup"
fi
mkdir -p priv
exec $CC \
$BASE_CFLAGS \
-I"$ERTS_INCLUDE_DIR" \
-Ic_src/lz4 \
${CFLAGS:-} \
$LDFLAGS \
-o "$TARGET" \
$SRCS