#!/usr/bin/env modbuild

SOURCE_URL="https://ftp.gnu.org/gnu/gcc/$P-$V/$P-$V.tar.bz2"

pbuild::patch_sources_Darwin() {
	if (( V_MAJOR == 4 && V_MINOR <= 8 )) || \
	   (( V_MAJOR == 4 && V_MINOR == 9 && V_PATCHLVL < 4)); then
		patch -p1 < "${BUILD_BLOCK_DIR}/${V_MAJOR}/non-dead-strip.patch"
		patch -p1 < "${BUILD_BLOCK_DIR}/${V_MAJOR}/configure-as.patch"
	fi
	if (( V_MAJOR == 5 )) || (( V_MAJOR == 6 )); then
		patch -p1 < "${BUILD_BLOCK_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" )
	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='/opt/local'
		"${MODULE_SRCDIR}"/configure \
			--prefix="${PREFIX}" \
			"${conf_args[@]}" \
			--with-as=${prefix}/bin/as \
			--with-ld=${prefix}/bin/ld \
			--with-ar=${prefix}/bin/ar \
			AR_FOR_TARGET=${prefix}/bin/ar \
			AS_FOR_TARGET=${prefix}/bin/as \
			LD_FOR_TARGET=${prefix}/bin/ld \
			NM_FOR_TARGET=${prefix}/bin/nm \
			OBJDUMP_FOR_TARGET=${prefix}/bin/objdump \
			RANLIB_FOR_TARGET=${prefix}/bin/ranlib \
			STRIP_FOR_TARGET=${prefix}/bin/strip \
			OTOOL=${prefix}/bin/otool \
			OTOOL64=${prefix}/bin/otool \
			|| exit 1
		;;
	Linux )
		"${MODULE_SRCDIR}"/configure \
			--prefix="${PREFIX}" \
			"${conf_args[@]}" \
			|| exit 1
		;;
	esac
}

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

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

