#!/bin/bash

to_uppercase() {
	printf '%s' "$1" | tr 'a-z' 'A-Z'
}

to_lowercase() {
	printf '%s' "$1" | tr 'A-Z' 'a-z'
}

opt_product_in() {
	switch="-DSSG_PRODUCT_$(to_uppercase "$1")=ON"
	echo "$switch"
}

is_product() {
	local candidate="$1"
	for cmake_product in "${all_cmake_products[@]}"; do
		if test "$(to_uppercase "$candidate")" = "$cmake_product"; then
			return 0
		fi
	done

	return 1
}

handle_wrong_argument() {
	all_cmake_lowercase=()
	for p in "${all_cmake_products[@]}"; do
		all_cmake_lowercase+=("$(to_lowercase "$p")")
	done
	possible_products=$'\n'"$(printf ' * %s\n' "${all_cmake_lowercase[@]}")"
	printf "Wipes out contents of the 'build' directory and builds only and only the given products."
	echo
	echo
	printf 'Usage:\n'
	printf '\tbuild-product [--debug] [--oval510] <product-name> [<product-name> ...]\n'
	echo
	if test -n "$1"; then
		printf "The argument '%s' is not supported.\\n" "$1"
	else
		printf 'Supply product names as arguments to this script.\n'
	fi
	printf 'Option --debug can be used to build draft profiles\n'
	printf 'Option --oval510 can be used to build Content with OVAL 5.10 (Default is 5.11)\n'

	printf 'Choose one or more product names from the list: %s' "$possible_products"
	echo
	exit 1
}

all_cmake_products=(
	CHROMIUM
	DEBIAN8
	EAP6
	EXAMPLE
	FEDORA
	FIREFOX
	FUSE6
	JRE
	OCP3
	OL7
	OL8
	OPENSUSE
	RHEL6
	RHEL7
	RHEL8
	RHOSP13
	RHV4
	SLE11
	SLE12
	UBUNTU1404
	UBUNTU1604
	UBUNTU1804
	WRLINUX8
	WRLINUX1019
)

if (( $# == 0 )); then
	handle_wrong_argument
fi

oval_minor_version="-DSSG_TARGET_OVAL_MINOR_VERSION:STRING=11"
build_type="-DCMAKE_BUILD_TYPE=Release"

# currently only two modifier options are available
for i in {1..2}; do
	if [[ "$1" == "--debug" ]]; then
		build_type="-DCMAKE_BUILD_TYPE=Debug"
		shift
	else
		if [[ "$1" == "--oval510" ]]; then
			oval_minor_version="-DSSG_TARGET_OVAL_MINOR_VERSION:STRING=10"
			shift
		fi
	fi
done

cmake_enable_args=()
for chosen_product in "$@"; do
	if is_product "$chosen_product"; then
		cmake_enable_args+=("$(opt_product_in "$chosen_product")")
	else
		handle_wrong_argument "$chosen_product"
	fi
done

cores=$(nproc 2>/dev/null) || cores=1

if which ninja &>/dev/null ; then
    cmake_generator="Ninja"
    build_command="ninja"
else
    cmake_generator="Unix Makefiles"
    build_command="make"
fi

set -e
rm -rf build/*
cd build
cmake .. "${build_type}" "${oval_minor_version}" -DSSG_PRODUCT_DEFAULT=OFF "${cmake_enable_args[@]}" -G "$cmake_generator"
$build_command "-j${cores}"
