#!/bin/sh

######### Default options ############
CC="gcc"
CXX="g++"
enable_lcms="no"
enable_openmp="no"
CFLAGS="-O4 -I. -w"
LDFLAGS=
DESTDIR=""
PREFIX="/usr/local"
lcms_headers="/usr/local/include"
lcms_libs="/usr/local/lib"
######################################

SRCFILE=

cleanup() {
	echo "Aborted, cleaning up"
	if [ -n "$SRCFILE" ]; then
		rm -f $SRCFILE
		rm -f $SRCFILE.out
	fi
	echo "Done"
	exit 1
}

check_lib() {
	fail=
	printf "Checking if lib$1 is present and can be linked against... "
	SRCFILE=$(mktemp --suffix=.c)

	echo "extern int $2(void); int main() {$2();}" > $SRCFILE

	$CC $SRCFILE -o $SRCFILE.out -L$3 -l$1 > /dev/null 2>&1

	if [ $? -ne 0 ]; then
		echo "no"
		fail="yes"
	else
		echo "yes"
		LDFLAGS="$LDFLAGS -L$3 -l$1"
	fi

	rm -f $SRCFILE
	rm -f $SRCFILE.out

	if [ "$fail" = "yes" ]; then
		echo "Configuration failed. lib$1 is missing"
		exit 2
	fi
}

usage() {
	printf >&2 "Usage: $0 [options]\n\n"
	printf >&2 "Where options are:\n"
	printf >&2 "\t-c\tC Compiler to use [gcc]\n"
	printf >&2 "\t-x\tC++ Compiler to use [g++]\n"
	printf >&2 "\t-P\tDefault installation prefix [/usr/local]\n"
	printf >&2 "\t-o\tBuild with OpenMP support [no]\n"
	printf >&2 "\t-l\tBuild with lcms support [no]\n"
	printf >&2 "\t-I\tlcms headers location [/usr/local/include]\n"
	printf >&2 "\t-L\tlcms library location [/usr/local/lib]\n"
	echo >&2
	printf >&2 "\t-h\tPrint this help text\n\n"

	exit 1
}

trap 'cleanup' SIGINT

args=`getopt "c:x:lohL:I:P:" $*`

if [ $? -ne 0 ]; then
	usage
fi

set -- $args

while [ $# -gt 0 ]; do
	case "$1" in
	-c)
		CC="$2"
		shift
		;;
	-x)
		CXX="$2"
		shift
		;;
	-l)	
		enable_lcms="yes"
		;;
	-I)
		lcms_headers="$2"
		shift
		;;
	-P)
		PREFIX="$2"
		shift
		;;
	-L)
		lcms_libs="$2"
		shift
		;;
	-o)	
		enable_openmp="yes"
		;;
	-h)
		usage
		;;
	--)	break
		;;
	esac
	shift
done

echo "Using C compiler as $CC"
echo "Using C++ compiler as $CXX"

printf "Enable lcms... "
if [ "$enable_lcms" = "yes" ]; then
	echo "yes"
	check_lib lcms cmsErrorAction $lcms_libs
	CFLAGS="$CFLAGS -DUSE_LCMS -I$lcms_headers"
else
	echo "no"
fi

printf "Enable openmp support... "
if [ "$enable_openmp" = "yes" ]; then
	CFLAGS="$CFLAGS -fopenmp"
	echo "yes"
else
	echo "no"
fi

# Generate makefile from Makefile.in
echo "Generating Makefile"

echo "# Makefile generated from configure script. Do not edit" > Makefile

echo "CC = $CC" >> Makefile
echo "CXX = $CXX" >> Makefile
echo "CFLAGS = $CFLAGS" >> Makefile
echo "CXXFLAGS = \$(CFLAGS)" >> Makefile
echo "LDFLAGS = $LDFLAGS" >> Makefile
echo "DESTDIR = $DESTDIR" >> Makefile
echo "PREFIX = $PREFIX" >> Makefile
echo "LIBDIR = lib" >> Makefile
echo "BINDIR = bin" >> Makefile

cat Makefile.in >> Makefile

echo "Done"
