# Description: C runtime (crt) for mingw-w64 toolchain
# URL: http://mingw-w64.org/
# Maintainer: Matt Housh, jaeger at crux dot ninja

name=mingw-w64-crt
version=11.0.0
release=1
source=(https://sourceforge.net/projects/mingw-w64/files/mingw-w64/mingw-w64-release/mingw-w64-v$version.tar.bz2 \
	http://ftpmirror.gnu.org/gnu/binutils/binutils-2.39.tar.xz \
	http://gcc.gnu.org/pub/gcc/releases/gcc-13.1.0/gcc-13.1.0.tar.xz)

build() {

	# build a stub sysroot gcc if mingw-w64-gcc isn't already installed; if it is, that will be used instead
	if [ ! -x /usr/bin/x86_64-w64-mingw32-gcc ]; then

		export SYSROOT="--with-sysroot=$SRC/sysroot"


		for T in {i686,x86_64}-w64-mingw32; do
			mkdir build-binutils-$T
			cd build-binutils-$T
			../binutils-2.39/configure --target=$T --disable-multilib --prefix=$SRC/sysroot $SYSROOT
			sed -i -e '/^MAKEINFO/s:=.*:= true:' Makefile
			make
			make install
			cd ..
		done

		export PATH=$SRC/sysroot/bin:$PATH

		for T in {i686,x86_64}-w64-mingw32; do
			mkdir build-headers-$T
			cd build-headers-$T
			../mingw-w64-v$version/mingw-w64-headers/configure --host=$T --prefix=$SRC/sysroot/$T
			make install
			if [ "$T" = "x86_64-w64-mingw32" ]; then
				ln -sv $SRC/sysroot/$T $SRC/sysroot/mingw
				ln -sv $SRC/sysroot/$T/lib $SRC/sysroot/$T/lib64
			fi
			cd ..
		done

		for T in {i686,x86_64}-w64-mingw32; do
			mkdir build-gcc-$T
			cd build-gcc-$T
			../gcc-13.1.0/configure --target=$T --disable-multilib --disable-nls --enable-threads=posix --prefix=$SRC/sysroot $SYSROOT
			make all-gcc
			make install-gcc
			cd ..
		done
	fi

	# now build the crt
	for T in {x86_64,i686}-w64-mingw32; do
		mkdir build-$T
		cd build-$T
		[[ "$T" = "x86_64-w64-mingw32" ]] && OPTS="--enable-lib64 --disable-lib32" || OPTS="--enable-lib32 --disable-lib64"
		../mingw-w64-v$version/mingw-w64-crt/configure --prefix=/usr/$T --host=$T $OPTS --enable-wildcard $SYSROOT
		make
		make DESTDIR=$PKG install
		cd ..
	done
}
