#!/bin/sh
set -eu

>config.mk

usage () {
	echo >&2 'usage: configure [--enable-sanitizers]'
	echo >&2 '                 [--enable-debug]'
	echo >&2 '                 [--disable-ssl]'
}

>config.h

while [ $# -gt 0 ]; do
	if [ x"$1" = x'--enable-debug' ]; then
		cat >>config.mk <<-EOF
			CFLAGS += -g
			LDFLAGS += -g
		EOF
	fi
	if [ x"$1" = x'--enable-sanitizers' ]; then
		cat >>config.mk <<-EOF
			LDFLAGS += -lasan
			SANITIZER_FLAGS  = -fsanitize=address
			SANITIZER_FLAGS += -fsanitize=undefined
			SANITIZER_FLAGS += -fsanitize=signed-integer-overflow
			SANITIZER_FLAGS += -fno-sanitize-recover=all
		EOF
	fi
	if [ x"$1" = x'--disable-ssl' ]; then
		cat >>config.h <<-EOF
			#define MATRIX_PROTOCOL_SCHEMA http
			#define MATRIX_SERVER_PORT 80
		EOF
	fi
	shift
done

# TODO: use pkg-config or curl-config?
cat >>config.mk <<-EOF
	LDFLAGS += $(pkg-config --libs libcurl)
	CFLAGS += $(pkg-config --cflags libcurl)
EOF

cat >>config.mk <<-EOF
	LDFLAGS += $(pkg-config --libs jansson)
	CFLAGS += $(pkg-config --cflags jansson)
EOF

# TODO: At this time, there is still some incompatibility between ncursesw and
# NetBSD curses that we need to address later.
# TODO: add a flag to choose a different curses lib?
if pkg-config ncursesw; then
	cat >>config.mk <<-EOF
		LDFLAGS += $(pkg-config --libs ncursesw)
		CFLAGS += $(pkg-config --cflags ncursesw)
	EOF
# TODO: add vanilla ncurses?
else
	cat >>config.mk <<-EOF
		LDFLAGS += -lcurses
	EOF
fi
