#!/usr/bin/make -f

# Install the win32-loader-standalone.exe as debian/tools/win32-loader/$(SUITE)/win32-loader.exe on the mirrors
BYHAND ?= yes

W32_VERSION := $(shell dpkg-parsechangelog | sed -rne 's,^Version: ([^-]+).*,\1,p')
W32_BYHAND_NAME := win32-loader_$(W32_VERSION)_all

B_D_PACKAGES := grub-pc cpio-win32 gzip-win32

PACKAGES_LIST := $(shell set -e; \
	for p in ${B_D_PACKAGES}; \
	do \
		if test `dpkg-query --showformat='x$${Source}x' --show $$p` = "xx"; \
		then \
			dpkg-query --showformat='$${Package;-25} $${Version;-25} http://ftp.debian.org/debian/pool/main/$${Package;1}/$${Package}\\n' --show $$p; \
		else \
			dpkg-query --showformat='$${Package;-25} $${Version;-25} http://ftp.debian.org/debian/pool/main/$${Source;1}/$${Source}\\n' --show $$p; \
		fi; \
	done)

BUILT_USING_LIST := $(shell set -e; \
	for p in ${B_D_PACKAGES}; \
	do \
		if test `dpkg-query --showformat='x$${Source}x' --show $$p` = "xx"; \
		then \
			dpkg-query --showformat='$${Package} (= $${Version}), ' --show $$p; \
		else \
			dpkg-query --showformat='$${Source} (= $${Version}), ' --show $$p; \
		fi; \
	done)

NSIS_VERSION  := $(shell dpkg-query -f='$${Version}' -W nsis )

%:
	dh $@

override_dh_auto_build:
	# Build the standalone version
	STANDALONE=yes dh_auto_build
	mv win32-loader.exe win32-loader-standalone.exe
	
	# Prepare the README file
	awk '{sub(/@PACKAGES_LIST@/,"$(PACKAGES_LIST)")}1 \
             {sub(/@NSIS_VERSION@/,"$(NSIS_VERSION)")}1 \
             {sub(/@W32_VERSION@/,"$(W32_VERSION)")}1' \
		debian/win32-loader_doc.txt > $(W32_BYHAND_NAME).txt
	cat debian/copyright >> $(W32_BYHAND_NAME).txt
	# Build the cdrom version
	dh_auto_build

override_dh_auto_clean:
	dh_auto_clean
	rm -f win32-loader-standalone.exe

override_dh_builddeb:
	dh_builddeb
ifeq ($(BYHAND),yes)
	cp win32-loader-standalone.exe ../$(W32_BYHAND_NAME).exe
	dpkg-distaddfile $(W32_BYHAND_NAME).exe byhand -

	cp $(W32_BYHAND_NAME).txt ../
	dpkg-distaddfile $(W32_BYHAND_NAME).txt byhand -
endif

override_dh_gencontrol:
	dh_gencontrol -- -Vw32-loader:built-using="$(BUILT_USING_LIST)"
