#!/bin/bash
set -e
cd -- "$(dirname -- "${0}")/../../.."

if [ -z "${cc_path}" ]; then
	cc_path="cc"
fi

readonly machine="$("${cc_path}" -dumpmachine)"

if [[ "${machine}" == *"-cygwin" ]]; then
	readonly use_flto=0
else
	readonly use_flto=1
fi

mk_slunk() {
	make -B CC="${cc_path}" MARCH=${2} MTUNE=${3} STATIC=1 STRIP=1 FLTO=${use_flto}
	cp -vf "frontend/bin/slunkcrypt" "out/_next_/slunkcrypt-${1}"
}

mkdir -p "out/_next_"

make -B CC="${cc_path}" clean

case "${machine}" in
	x86_64*)
		mk_slunk "x86_64" "x86-64" "nocona"
		;;
	i686*)
		mk_slunk "i686" "pentiumpro" "pentium3"
		;;
	*)
		echo "Unknown target CPU type !!!"
		exit 1
esac

if [[ "${machine}" == *"-cygwin" ]]; then
	cp -vfu "$(which cygwin1.dll)" "out/_next_"
fi

echo "Build completed successfully."
