#! /usr/bin/env bash

panic()
{
	echo "ERROR: $*"
	exit 1
}

usage()
{
	if [ $# -ne 0 ]; then
		echo "BAD USAGE: $*"
	fi
	cat <<- EOF
	Usage
	=====

	$0 [options]

	Options
	=======

	-b \$build_dir
	    Set the build directory to \$build_dir.
	-i \$install_dir
	    Set the install directory to \$install_dir.
	-v
	    Enable verbose mode.
	-h
	    Print help information and exit.
	EOF
	exit 2
}

program_dir=$(dirname "$0") || exit 1
top_dir="$program_dir/.."

verbose=0
build_dir=
install_dir=
tmp_dir=
mode=release
strict=0

while getopts vb:i:t:drs opt; do
	case $opt in
	s)
		strict=1;;
	r)
		mode=release;;
	d)
		mode=debug;;
	b)
		build_dir="$OPTARG";;
	i)
		install_dir="$OPTARG";;
	v)
		verbose=$((verbose + 1));;
	h)
		usage;;
	\?)
		usage;;
	esac
done
shift $((OPTIND - 1))

if [ -z "$tmp_dir" ]; then
	tmp_dir="$top_dir/tmp_cmake"
fi
if [ -z "$build_dir" ]; then
	build_dir="$tmp_dir/build"
fi
if [ -z "$install_dir" ]; then
	install_dir="$tmp_dir/install"
fi

cmake --version || panic "cannot run cmake"

configure_options=()

configure_options+=(-DCMAKE_INSTALL_PREFIX="$install_dir")

if [ "$verbose" -ge 1 ]; then
	configure_options+=(-DCMAKE_VERBOSE_MAKEFILE=1)
fi

if [ "$mode" = debug ]; then
	configure_options+=(-DCMAKE_BUILD_TYPE=Debug)
	configure_options+=(-DXV_ENABLE_ASAN=1)
	configure_options+=(-DXV_ENABLE_UBSAN=1)
fi
if [ "$strict" -ne 0 ]; then
	configure_options+=(-DXV_STRICT=1)
fi

cmake "${configure_options[@]}" -H"$top_dir" -B"$build_dir" || \
  panic "configure failed"

cmake --build "$build_dir" || panic "build failed"

cmake --build "$build_dir" --target install || panic "install failed"
