#!/usr/bin/make -f

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

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_CFLAGS_MAINT_APPEND = -fPIE -D_FORTIFY_SOURCE=2
export DEB_LDFLAGS_MAINT_APPEND = -fPIE -pie

PACKAGE = binutils-msp430
TARGET = msp430
BINUTILS_VER := $(shell dpkg-query -W -f="\$${Version}\n" binutils-source)


DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

ifeq ($(DEB_HOST_ARCH),ppc64el)
export DEB_CFLAGS_MAINT_STRIP = -O3
export DEB_CFLAGS_MAINT_APPEND = -O2
endif

BUILD_TREE = $(shell find . -maxdepth 1 -mindepth 1 -type d -name 'binutils*')
DEB_BINUTILS = .

CONFARGS = --target=$(TARGET) \
           --libdir=/usr/lib/$(TARGET) \
           --with-system-zlib \
           --enable-deterministic-archives \
           --disable-static


%:
	dh $@

unpack-stamp:
	cp -a /usr/src/binutils/binutils-*.tar.* .
	tar xf $(DEB_BINUTILS)/binutils-*.tar.*
	touch unpack-stamp

override_dh_auto_configure: unpack-stamp
	DH_COMPAT=10 dh_auto_configure --sourcedirectory=$(BUILD_TREE) -- $(CONFARGS)

override_dh_auto_build:
	patch -p1 < debian/patches/fix-spelling-error-in-binary
	dh_auto_build --sourcedirectory=$(BUILD_TREE)
	patch -p1 < debian/patches/fix-manpage

override_dh_auto_clean:
	rm -rf $(BUILD_TREE)
	rm -rf $(DEB_BINUTILS)/binutils-*
	dh_auto_clean

override_dh_auto_install:
	dh_auto_install --sourcedirectory=$(BUILD_TREE)

	# Remove conflicting files
	cd debian/$(PACKAGE)/usr && \
	rm -rf lib/libiberty.* lib/libbfd.* lib/libopcodes* \
	include/bfd.h include/ansidecl.h include/bfdlink.h \
	share/locale include/symcat.h include/dis-asm.h \
	info share/info
	# fix manpage issues
	cd debian/$(PACKAGE)/usr/share/man/man1 && \
	rm -rf msp430-dlltool.1 msp430-windmc.1 msp430-windres.1 && \
	ln -s msp430-ld.1  msp430-ld.bfd.1
	# clean hardlinks
	cd debian/$(PACKAGE)/usr && \
	rm -rf msp430

override_dh_gencontrol:
	dh_gencontrol -- -Vbinutils:Version=$(BINUTILS_VER)
