#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
# export DH_VERBOSE=1

DEB_HOST_MULTIARCH := $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
PACKAGE_NAME := $(shell dpkg-parsechangelog | sed -n -e's/^Source: \(.*\)\+/\1/p')
DVERSION := $(shell dpkg-parsechangelog | grep ^Version | sed -e 's/^Version: //')
UVERSION := $(shell echo $(DVERSION) | cut -d- -f1)
P_SRC := debian/newlib-source
TARGET := arm-none-eabi
CFLAGS := CFLAGS="-g -O2 -fno-unroll-loops -ffunction-sections -fdata-sections"
TARGET_TOOLS =  \
				CC_FOR_TARGET=$(TARGET)-gcc \
				GCC_FOR_TARGET=$(TARGET)-gcc \
				AR_FOR_TARGET=$(TARGET)-ar \
				AS_FOR_TARGET=$(TARGET)-as \
				LD_FOR_TARGET=$(TARGET)-ld \
				NM_FOR_TARGET=$(TARGET)-nm \
				OBJDUMP_FOR_TARGET=$(TARGET)-objdump \
				RANLIB_FOR_TARGET=$(TARGET)-ranlib \
				READELF_FOR_TARGET=$(TARGET)-readelf \
				STRIP_FOR_TARGET=$(TARGET)-strip

CONFIGURE_FLAGS = \
	--host=$(DEB_HOST_MULTIARCH) \
	--target=$(TARGET) \
	--prefix=/usr/lib \
	--libdir=/usr/lib \
	--infodir=/usr/share/doc/$(PACKAGE_NAME)/info \
	--mandir=/usr/share/man \
	--htmldir=/usr/share/doc/$(PACKAGE_NAME)/html \
	--pdfdir=/usr/share/doc/$(PACKAGE_NAME)/pdf \
	--with-pkgversion=$(DVERSION) \
	--enable-newlib-io-long-long \
	--enable-newlib-register-fini \
	--disable-newlib-supplied-syscalls \
	--disable-nls \
	$(CFLAGS) \
	$(TARGET_TOOLS)

%:
	dh $@ -Bbuild --with autotools-dev --parallel

override_dh_clean:
	dh_clean
	rm -rf build
	rm -rf $(P_SRC)

override_dh_auto_configure:
	dh_auto_configure -Bbuild -- $(CONFIGURE_FLAGS)

override_dh_auto_install:
	dh_auto_install --max-parallel=1
	rm -rf debian/libnewlib-dev/usr/include/newlib/bits
	rm -rf debian/libnewlib-dev/usr/include/newlib/rpc
	# Build newlib-source package
	mkdir -p $(P_SRC)/usr/src/newlib
	cp ../newlib_$(UVERSION).orig.tar.gz $(P_SRC)/usr/src/newlib/newlib-$(UVERSION).tar.gz
	gunzip $(P_SRC)/usr/src/newlib/newlib-$(UVERSION).tar.gz
	xz -z $(P_SRC)/usr/src/newlib/newlib-$(UVERSION).tar
	mkdir -p $(P_SRC)/usr/src/newlib/patches
	cp debian/patches/* $(P_SRC)/usr/src/newlib/patches

override_dh_installchangelogs:
	dh_installchangelogs ChangeLog

override_dh_installdocs:
	set -ex; \
		cd build/$(TARGET)/newlib; \
		make html-recursive; \
		cd -;
	dh_installdocs
