#!/bin/sh

config_mk="config.mk"
enable_asan=f
prefix="/usr/local"
with_xfce4_panel_applet=f
with_gtktheme=f
with_lx=f
with_pmenu=f

usage_message="Usage: ./configure
Produce a config.mk file to be sourced by Makefile
--with-xfce4-panel-applet  Include xfce4-panel-applet. This has quite different
                           runtime dependencies, so consider building
			   separately.
--with-gtktheme            Include gtktheme module
--with-lx                  Include lx module
--with-pmenu               Include pmenu module
--all, -a                  Include all contrib/ packages above
--dev, -d                  Same as --all, but also with ASAN and prefix=\$HOME
--enable-asan              Enable address sanitizer (only during development)
--prefix=<dir>             Install architecture-independent files in \$prefix
                           (e.g. --prefix=\$HOME')
--libdir=<dir>             Specify libdir (\$prefix/lib by default)
--libexecdir=<dir>         Specify libexecdir (\$prefix/lib by default)
"

print_ok_fail () {
	# Usage: print_ok_fail <status> <message>...
	# <status> 0=ok; 1-127=fail
	status=$1
	shift
	if [ "$status" = "0" ]; then
		printf '%b\n' "[ OK ] $*"
	else
		printf '%b\n' "[FAIL] $*"
		exit 1
	fi
}

check_bin () {
	type "$*" >/dev/null 2>&1
	print_ok_fail $? $*
}

check_lib () {
	pkg-config "$*" >/dev/null 2>&1
	print_ok_fail $? $*
}

check_core_dependencies () {
	for b in "pkg-config" "xml2-config"; do
		check_bin "$b"
	done
	for l in "x11" "xrandr" "cairo" "pango" "pangocairo" "librsvg-2.0" "glib-2.0"; do
		check_lib "$l"
	done
}

add () {
	printf '%b\n' "$*" >>"$config_mk"
}

add_modules () {
	add "prefix = $prefix"
	test -z "$libdir" || add "libdir = $libdir"
	test -z "$libexecdir" || add "libexecdir = $libexecdir"
	if [ "$enable_asan" = "t" ]; then
		add "ASAN=1"
	fi
	if [ "$with_xfce4_panel_applet" = "t" ]; then
		check_lib "libxfce4panel-2.0"
		add "CONTRIB_DIRS += xfce4-panel"
	fi
	if [ "$with_gtktheme" = "t" ]; then
		add "CONTRIB_DIRS += gtktheme"
	fi
	if [ "$with_lx" = "t" ]; then
		check_lib "libmenu-cache >= 1.1.0"
		add "CONTRIB_DIRS += lx"
	fi
	if [ "$with_pmenu" = "t" ]; then
		add "CONTRIB_DIRS += pmenu"
	fi
}

with_all () {
	with_xfce4_panel_applet=t
	with_gtktheme=t
	with_lx=t
	with_pmenu=t
}

main () {
	for arg
	do
		opt=${arg%%=*}
		var=${arg#*=}
		case "$opt" in
		--prefix)
			prefix="$var" ;;
		--libdir)
			libdir="$var" ;;
		--libexecdir)
			libexecdir="$var" ;;
		--with-xfce4-panel-applet)
			with_xfce4_panel_applet=t ;;
		--with-gtktheme)
			with_gtktheme=t ;;
		--with-lx)
			with_lx=t ;;
		--with-pmenu)
			with_pmenu=t ;;
		--enable-asan)
			enable_asan=t ;;
		-a|--all)
			with_all ;;
		-d|--dev)
			with_all
			enable_asan=t
			prefix=${HOME}
			;;
		-h|--help)
			printf '%b' "$usage_message"; exit 1 ;;
		*)
			printf '%b\n' "warn: unknown option $opt" >&2 ;;
		esac
	done

	rm -rf $config_mk
	add "# Generated by configure script"
	check_core_dependencies
	add_modules
}

main "$@"
