#!/usr/bin/env modbuild

pbuild::set_download_url "https://ftp.gnu.org/gnu/gcc/$P-$V/$P-$V.tar.gz"

pbuild::patch_sources_Darwin() {
	if (( V_MAJOR == 4 && V_MINOR <= 8 )) || \
	   (( V_MAJOR == 4 && V_MINOR == 9 && V_PATCHLVL < 4)); then
		patch -p1 < "${BUILDBLOCK_DIR}/${V_MAJOR}/non-dead-strip.patch"
		patch -p1 < "${BUILDBLOCK_DIR}/${V_MAJOR}/configure-as.patch"
	fi
	if (( V_MAJOR == 5 )) || (( V_MAJOR == 6 )); then
		patch -p1 < "${BUILDBLOCK_DIR}/${V_MAJOR}/PR57438_avoiding_empty_function_bodies_and_trailing_labels.patch"
	fi
}

pbuild::configure() {
	local -a conf_args=()
	conf_args+=( "--enable-languages=c,c++,objc,obj-c++,lto,fortran,go" )
	conf_args+=( "--with-gmp=${GMP_PREFIX}" )
	conf_args+=( "--with-mpfr=${MPFR_PREFIX}" )
	conf_args+=( "--with-mpc=${MPC_PREFIX}" )
	conf_args+=( "--enable-lto" )
	conf_args+=( "--disable-multilib" )
	conf_args+=( "--with-build-config=bootstrap-debug" )
	conf_args+=( "--with-pkgversion='PSI Environment Module'" )
	conf_args+=( "--with-build-config=bootstrap-debug" )

	case "${OS}" in
	Darwin )
		local -r prefix='/usr'
		conf_args+=( "--with-as=${prefix}/bin/as" )
		conf_args+=( "--with-ld=${prefix}/bin/ld" )
		conf_args+=( "--with-ar=${prefix}/bin/ar" )
		export	AR_FOR_TARGET=${prefix}/bin/ar \
		export	AS_FOR_TARGET=${prefix}/bin/as \
		export	LD_FOR_TARGET=${prefix}/bin/ld \
		export	NM_FOR_TARGET=${prefix}/bin/nm \
		export	OBJDUMP_FOR_TARGET=${prefix}/bin/objdump \
		export	RANLIB_FOR_TARGET=${prefix}/bin/ranlib \
		export	STRIP_FOR_TARGET=${prefix}/bin/strip \
		export	OTOOL=${prefix}/bin/otool \
		export	OTOOL64=${prefix}/bin/otool \
		;;
	* )
		echo "Unsupported OS '${OS}'!"
		;;
	esac
	"${SRC_DIR}"/configure \
		--prefix="${PREFIX}" \
		"${conf_args[@]}" \
		|| exit 1
}

# use system gcc to compile
declare -rx CC=gcc
declare -rx CXX=g++

pbuild::add_to_group 'Programming'
pbuild::install_docfiles 'COPYING' 'COPYING.LIB' 'COPYING.RUNTIME' 'COPYING3' 'COPYING3.LIB' 'NEWS' 'README'
pbuild::make_all

