#!/bin/sh

test_libc_features() {
	CFLAGS="-D_GNU_SOURCE"
	: ${CC:=cc}
	2>/dev/null $CC -xc $CFLAGS - <<-EOF
	#include <string.h>
	#include <stdlib.h>
	int main(void) {
		char dst[4];
		unsigned rnd;
		strlcpy(dst, "1234", sizeof dst);
		rnd = arc4random();
		return 0;
	}
	EOF
}

usage() {
	cat <<-HELP
	Usage: configure [-h]
	Example: build and install to your home directory

	./configure
	CFLAGS="-static" make
	PREFIX=\$HOME/local make install
	HELP
	exit 1
}

copy_mk() {
	cmd="cp Makefile.$1 Makefile"
	echo "+ $cmd"; $cmd
}

copy_tests_mk() {
	cmd="cp tests/Makefile.$1 tests/Makefile"
	echo "+ $cmd"; $cmd
}

while [ $# -gt 0 ]; do
	case $1 in
		-h) usage ;;
		 *) echo "configure: unused argument: $1" ;;
	esac
	shift
done

case "${TARGET_OS:-`uname`}" in
	Darwin)
		copy_mk macos
		copy_tests_mk bsd
		;;
	FreeBSD)
		copy_mk freebsd
		copy_tests_mk bsd
		;;
	Linux)
		test_libc_features && copy_mk linux || copy_mk linux-compat
		copy_tests_mk linux
		;;
	*)
		copy_mk bsd
		copy_tests_mk bsd
		;;
esac

# vim:noexpandtab:syntax=sh:ts=4
