# This file is part of the FreeWRT project. FreeWRT is copyrighted
# material, please see the LICENCE file in the top-level directory

include $(TOPDIR)/rules.mk
include ../rules.mk

GCC_VERSION:=14.3.0
GCC_SITE:=@GNU/gcc/gcc-$(GCC_VERSION)
GCC_MD5SUM:=1ba56546c0274ea75457bf5c00c61506
SOURCE:=gcc-$(GCC_VERSION).tar.gz
GCC_DIR:=$(TOOLCHAIN_BUILD_DIR)/gcc-$(GCC_VERSION)

TARGET_LANGUAGES:=c,c++

GCC_BUILD_DIR1:=$(TOOLCHAIN_BUILD_DIR)/gcc-$(GCC_VERSION)-initial

$(DL_DIR)/$(SOURCE):
	mkdir -p $(DL_DIR)
	$(SCRIPT_DIR)/download.pl $(DL_DIR) $(SOURCE) $(GCC_MD5SUM) $(GCC_SITE)

$(GCC_DIR)/.unpacked: $(DL_DIR)/$(SOURCE)
	${EXTRACT_CMD}
	touch $@

$(GCC_BUILD_DIR1)/.configured: $(GCC_DIR)/.unpacked
	mkdir -p $(GCC_BUILD_DIR1)
	(cd $(GCC_BUILD_DIR1); rm -f config.cache; PATH=$(TARGET_PATH) \
		$(GCC_DIR)/configure \
		--prefix=$(STAGING_DIR)/usr \
		--build=$(GNU_HOST_NAME) \
		--host=$(GNU_HOST_NAME) \
		--target=$(GNU_TARGET_NAME) \
		--with-gmp=$(STAGING_HOST_DIR)/usr \
		--with-mpfr=$(STAGING_HOST_DIR)/usr \
		--enable-languages=c \
		--with-system-zlib \
		--with-newlib \
		--disable-shared \
		--disable-threads \
		--enable-tls \
		--enable-__cxa_atexit \
		--enable-target-optspace \
		--with-gnu-ld \
		--with-gnu-as \
		--disable-nls \
		--enable-largefile \
		--without-headers \
	);
	touch $@

$(GCC_BUILD_DIR1)/.compiled: $(GCC_BUILD_DIR1)/.configured
	PATH=$(TARGET_PATH) $(MAKE) -C $(GCC_BUILD_DIR1) all-gcc all-target-libgcc
	touch $@

$(STAGING_DIR)/bin/$(GNU_TARGET_NAME)-gcc: $(GCC_BUILD_DIR1)/.compiled
	PATH=$(TARGET_PATH) $(MAKE) -C $(GCC_BUILD_DIR1) install-gcc install-target-libgcc

GCC_BUILD_DIR2:=$(TOOLCHAIN_BUILD_DIR)/gcc-$(GCC_VERSION)-final
$(GCC_BUILD_DIR2)/.configured: $(STAGING_DIR)/usr/lib/libc.a
	mkdir -p $(GCC_BUILD_DIR2)
	(cd $(GCC_BUILD_DIR2); rm -f config.cache; PATH=$(TARGET_PATH) \
		$(GCC_DIR)/configure \
		--prefix=$(STAGING_DIR)/usr \
		--build=$(GNU_HOST_NAME) \
		--host=$(GNU_HOST_NAME) \
		--target=$(GNU_TARGET_NAME) \
		--with-gmp=$(STAGING_HOST_DIR)/usr \
		--with-mpfr=$(STAGING_HOST_DIR)/usr \
		--enable-languages=$(TARGET_LANGUAGES) \
		--with-system-zlib \
		--disable-libsanitizer \
		--enable-shared \
		--enable-tls \
		--enable-libatomic \
		--with-sysroot=$(STAGING_DIR) \
		--enable-__cxa_atexit \
		--enable-target-optspace \
		--with-gnu-ld \
		--with-gnu-as \
		--disable-nls \
		--enable-largefile \
	);
	touch $@

$(GCC_BUILD_DIR2)/.compiled: $(GCC_BUILD_DIR2)/.configured
	PATH=$(TARGET_PATH) $(MAKE) -C $(GCC_BUILD_DIR2) all
	touch $@

gcc-install: $(GCC_BUILD_DIR2)/.compiled
	PATH=$(TARGET_PATH) $(MAKE) -C $(GCC_BUILD_DIR2) install
	echo $(GCC_VERSION) > $(STAGING_DIR)/gcc_version

source: $(DL_DIR)/$(SOURCE)
prepare: $(STAGING_DIR)/bin/$(GNU_TARGET_NAME)-gcc
compile: gcc-install
install:
clean: gcc-clean
	rm -rf $(GCC_DIR)
	rm -rf $(GCC_BUILD_DIR1)
	rm -rf $(GCC_BUILD_DIR2)
	rm -f $(STAGING_DIR)/bin/$(GNU_TARGET_NAME)-gc*
	rm -f $(STAGING_DIR)/bin/$(GNU_TARGET_NAME)-c*
