#!/usr/bin/env bash

set -e
set -o pipefail

compile="$0"
JOBS="$(getconf _NPROCESSORS_ONLN)"
V="${V:+V=1}"

clean()
{
	make clean

	local CLEAN=$(git clean -n -fdx)
	if [ -n "$CLEAN" ]
	then
		echo "$compile: Unclean:" >&2
		echo "$CLEAN" >&2
		exit 1
	fi
}

make_jv()
{
	make -j"$JOBS" $V $@
}

which_mac_homebrew_gcc()
{
	local prefix="${HOMEBREW_PREFIX:-$(brew --prefix)}"
	local path="$(find -L "$prefix/bin" -name 'gcc-[0-9]*' 2>/dev/null |
		sort -Vr | head -n1)"

	if [ -z "$path" ]
	then
		echo "$compile: Error: Homebrew gcc-<n> not found." >&2
		exit 1
	fi

	echo "$path"
}

arch()
{
	[ -z "$1" ] && exit

	echo "$compile $@ JOBS=$JOBS" $V
	clean

	case "$1" in
	cross)
		arch atari-st web "$(uname -m)"
		;;
	atari-st)
		m68k-elf-gcc --version | sed -n 1p
		make_jv S=1 TARGET_COMPILE=m68k-elf- PSGPLAY.TOS lib/tos/tos
		;;
	test)
		m68k-elf-gcc --version | sed -n 1p
		make_jv S=1 TARGET_COMPILE=m68k-elf- test
		;;
	verify)
		m68k-elf-gcc --version | sed -n 1p
		make_jv S=1 TARGET_COMPILE=m68k-elf- verify
		make_jv S=1 TARGET_COMPILE=m68k-elf- report
		;;
	mac)
		cc --version | sed -n 1p
		make_jv psgplay example
		;;
	mac-homebrew-gcc-portaudio)
		local HOMEBREW_GCC="$(which_mac_homebrew_gcc)"
		echo "$HOMEBREW_GCC $("$HOMEBREW_GCC" --version | sed -n 1p)"
		make_jv PORTAUDIO=1 CC="$HOMEBREW_GCC" LD=/usr/bin/clang
		;;
	web)
		emcc --version | sed -n 1p
		make_jv HOST_CC=emcc web
		;;
	ppc64le |\
	aarch64)
		cc --version | sed -n 1p
		make_jv ALSA=1 all test global
		;;
	x86_64)
		gcc --version | sed -n 1p
		make_jv S=1 ALSA=1 CC=gcc all test
		clean

		clang --version | sed -n 1p
		make_jv S=1 ALSA=1 CC=clang psgplay
		clean

		cc --version | sed -n 1p
		make_jv psgplay
		clean

		cc --version | sed -n 1p
		make_jv ALSA=1 psgplay global
		;;
	*)
		echo "$compile: '$1' is not an arch." >&2
		exit 1
	esac

	shift
	arch "$@"
}

case "$1" in
arch)
	shift
	arch "$@"
	;;
*)
	echo "$compile: '$1' is not a command." >&2
	exit 1
esac
