#!/usr/bin/make -f

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

PACKAGE=gcc-msp430
TARGET=msp430
VERSION = $(shell dpkg-parsechangelog | sed -n 's/^Version:.*\(msp.*\)-.*$$/\1/p')

CONFARGS = -v \
           --enable-languages=c,c++ \
           --prefix=/usr \
           --with-system-zlib \
           --infodir=\$${prefix}/share/info \
           --mandir=\$${prefix}/share/man \
           --bindir=\$${prefix}/bin \
           --libexecdir=\$${prefix}/lib \
           --libdir=\$${prefix}/lib \
           --build=$(DEB_BUILD_GNU_TYPE) \
           --host=$(DEB_HOST_GNU_TYPE) \
	   MAKEINFO=missing \
           --target=$(TARGET)

BUILD_TREE = $(shell find . -maxdepth 1 -mindepth 1 -type d -name 'gcc*')
DEB_SOURCE = ./
BUILD_RES = build-result

unpack: unpack-stamp
unpack-stamp: 
	tar xaf $(DEB_SOURCE)/gcc-*.tar.*
	touch unpack-stamp

patch-stamp: unpack-stamp
	cd $(BUILD_TREE) && \
	for upstreamp in `grep -v '^#' $(CURDIR)/debian/patchlist`; \
		do echo; echo Applying patch $$upstreamp; \
		patch -p1 < $(CURDIR)/debian/$$upstreamp; done
	touch patch-stamp

configure: configure-stamp
configure-stamp: patch-stamp
	dh_testdir
	dh_update_autotools_config
	dh_autoreconf
	mkdir -p $(BUILD_RES)
	sed -i 's/BUILD_INFO=info/BUILD_INFO=/' $(BUILD_TREE)/configure
	cd $(BUILD_RES) && $(CURDIR)/$(BUILD_TREE)/configure $(CONFARGS)
	touch configure-stamp

build: build-arch build-indep
build-arch: build-stamp
build-indep: build-stamp
build-stamp: configure-stamp
	dh_testdir
	$(MAKE) $(MAKEFLAGS) -C $(BUILD_RES)
	touch build-stamp

clean:
	dh_testdir
	dh_testroot
	rm -f build-stamp configure-stamp unpack-stamp patch-stamp
	rm -rf $(BUILD_TREE) 
	rm -rf $(BUILD_RES) 
	dh_autoreconf_clean
	dh_clean

install: build
	dh_testdir
	dh_testroot
	dh_prep
	dh_installdirs

	$(MAKE) $(MAKEFLAGS) -C $(BUILD_RES) install prefix=$(CURDIR)/debian/$(PACKAGE)/usr

	# Remove conflicting and empty files
	rm -rf debian/$(PACKAGE)/usr/share/info
	rm -rf debian/$(PACKAGE)/usr/share/man
	rm -rf debian/$(PACKAGE)/usr/msp430/
	rm -rf debian/$(PACKAGE)/usr/lib/libiberty.a

binary-indep: install

binary-arch: install
	dh_testdir
	dh_testroot
	dh_installdocs -n
	dh_installman
	dh_installchangelogs
	dh_link
	# We'd really need cross-stripping here, instead
	dh_strip -Xlibgcc.a -Xlibcrt0.a -Xcrt0ivtbl64.o \
		 -Xlibgcov.a -Xlibcrt0dwdt.a -Xcrt0ivtbl16.o \
		 -Xcrt0ivtbl32.o 
	dh_compress
	dh_fixperms
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install configure
