#! /usr/bin/make -f

ARCH=$(shell dpkg-architecture -qDEB_BUILD_ARCH)
VERSION=$(shell LC_ALL=C dpkg-parsechangelog | grep ^Version: | cut -d ' ' -f 2)
SUITE=$(shell LC_ALL=C dpkg-parsechangelog | grep ^Distribution: | cut -d ' ' -f 2 | cut -d - -f 1)
ifeq (${SUITE},UNRELEASED)
USE_UDEBS_FROM=focal
TRANSSTATUS=
BOOTMENU_BEEP=n
else
USE_UDEBS_FROM=$(SUITE)
USE_PROPOSED_UPDATES=0
TRANSSTATUS=translation-status
BOOTMENU_BEEP=y
endif

ARCHIVEDIR=debian/tmp/installer-$(ARCH)
DESTDIR=$(ARCHIVEDIR)/$(VERSION)
IMAGEDIR=$(DESTDIR)/legacy-images
TARNAME=debian-installer-images_$(VERSION)_$(ARCH).tar.gz

export NO_PNG_PKG_MANGLE=1

clean:
	dh_testdir
	dh_testroot
	dh_clean
	$(MAKE) -C build reallyclean
	$(MAKE) -C doc/devel/partman clean
	$(MAKE) -C doc/devel/internals clean

# Must run as root, so is not run as part of regular build.
build-images:
	$(MAKE) -C build all_build stats release \
		USE_UDEBS_FROM=$(USE_UDEBS_FROM) BUILD_DATE=$(VERSION) \
		USE_PROPOSED_UPDATES=$(USE_PROPOSED_UPDATES) \
		TRANSSTATUS=$(TRANSSTATUS) BOOTMENU_BEEP=$(BOOTMENU_BEEP)
	
build: build-stamp
build-stamp:
	rm -f $@
	$(MAKE) -C doc/devel/internals
	$(MAKE) -C doc/devel/partman
	touch $@

install: build
	dh_testdir
	dh_testroot
	dh_prep
	dh_installdirs
	
	#debian/rules build-images

	install -d $(IMAGEDIR)
	#cp -a build/dest/* $(IMAGEDIR)
	ln -s $(VERSION) $(ARCHIVEDIR)/current

binary-arch: install  
	dh_testdir
	dh_testroot
	dh_installchangelogs
	dh_installdocs doc/* -X Makefile -X build.sh -X .xsl \
		-X internals.xml -X partman-doc.sgml
	dh_compress
	dh_fixperms

	# Only depend on the packages, not versions, at least for now:
	#echo -n "udeb:Depends=" >> debian/debian-installer-udebs.substvars
	#while read p v a; do \
	#	echo -n "$$p, " >> debian/debian-installer-udebs.substvars; \
	#done < build/dest/udeb.list
	#echo "" >> debian/debian-installer-udebs.substvars
	dh_gencontrol
	dh_md5sums
	dh_builddeb
	#cp debian/*.html $(IMAGEDIR)
	cp debian/index.html $(IMAGEDIR)
	cd debian/tmp && tar czvf ../../../$(TARNAME) .
	dpkg-distaddfile $(TARNAME) raw-installer -

binary-indep:

binary: binary-indep binary-arch

bump-kernel: PROPOSED=$(shell rmadison -s $(USE_UDEBS_FROM)-proposed linux | cut -d\  -f4 | sed 's/\.[0-9]*$$//')
bump-kernel: UPDATES=$(shell rmadison -s $(USE_UDEBS_FROM)-updates linux | cut -d\  -f4 | sed 's/\.[0-9]*$$//')
bump-kernel: RELEASE=$(shell rmadison -s $(USE_UDEBS_FROM) linux | cut -d\  -f4 | sed 's/\.[0-9]*$$//')
bump-kernel: BASEVERSION=$(firstword $(PROPOSED) $(UPDATES) $(RELEASE))

bump-kernel:
	sed -i 's/BASEVERSION = .*/BASEVERSION = $(BASEVERSION)/' build/config/*.cfg
	bzr diff || dch 'Move master kernels to $(BASEVERSION).'

.PHONY: build build-images clean binary-indep binary-arch binary install bump-kernel
