#!/usr/bin/make -f

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

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_HOST_GNU_CPU ?= $(shell dpkg-architecture -qDEB_HOST_GNU_CPU)
DEB_HOST_GNU_SYSTEM ?= $(shell dpkg-architecture -qDEB_HOST_GNU_SYSTEM)

VERSION = $(shell dpkg-parsechangelog | grep ^Version: | cut -d ' ' -f 2)
EXTRA_VERSION = Debian $(VERSION)

ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS)))
	CONFIG_DEBUG = true
endif
ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
endif

export EXTRA_VERSION CONFIG_DEBUG

PACKAGE_PREFIX = busybox

PACKAGES_DEB = $(PACKAGE_PREFIX) 

DEBHELPER_PACKAGES_DEB = $(patsubst %,-p%,$(PACKAGES_DEB))

CONFIG = $(firstword $(wildcard ./$(DEBIAN_DIR)/config-$(1)-$(DEB_HOST_GNU_SYSTEM)-$(DEB_HOST_GNU_CPU) ./$(DEBIAN_DIR)/config-$(1)-$(DEB_HOST_GNU_SYSTEM) ./$(DEBIAN_DIR)/config-$(1)))
CONFIG_DEB = $(call CONFIG,deb)

build-arch: build-arch-deb

.NOTPARALLEL: build-arch-deb build-arch-static build-arch-udeb build-arch-floppy-udeb

build-arch-deb: build-arch-deb-stamp
build-arch-deb-stamp: 
	$(MAKE) clean

	cp $(CONFIG_DEB) .config

	$(MAKE) dep
	$(MAKE)

	install -d \
		install-$(PACKAGE_PREFIX)/bin 
	#	install-$(PACKAGE_PREFIX)/usr/share/man/man1
	install busybox install-$(PACKAGE_PREFIX)/bin/busybox
	#install docs/BusyBox.1 install-$(PACKAGE_PREFIX)/usr/share/man/man1/busybox.1

	touch $@

build: build-arch

clean:
	dh_testdir
	dh_testroot
	rm -f build-*-stamp

	-$(MAKE) distclean
	-rm -rf install* busybox.1
	-rm -f $(DEBIAN_DIR)/busybox.links

	dh_clean

install-deb: build-arch-deb
	dh_testdir
	dh_testroot
	dh_clean -k $(DEBHELPER_PACKAGES_DEB)
	dh_installdirs $(DEBHELPER_PACKAGES_DEB)

	for i in $(PACKAGES_DEB); do \
	( \
		cd install-$$i; \
		find -type d -exec install -d $(CURDIR)/$(DEBIAN_DIR)/$$i/{} \;; \
		find \( -type f -o -type l \) -exec cp -a {} $(CURDIR)/$(DEBIAN_DIR)/$$i/{} \;; \
	); \
	done

	sed -e 's,^/,bin/busybox ,' busybox.links | grep -v linuxrc >  $(DEBIAN_DIR)/busybox.links

	#install -m644 $(DEBIAN_DIR)/$(PACKAGE_PREFIX)-static.override \
	#	$(DEBIAN_DIR)/$(PACKAGE_PREFIX)-static/usr/share/lintian/overrides/$(PACKAGE_PREFIX)-static

binary-arch: binary-arch-deb

# Build architecture-dependent files here.
binary-arch-deb: build-arch-deb install-deb
	dh_testdir
	dh_testroot
	#install $(DEBIAN_DIR)/local/bash $(DEBIAN_DIR)/busybox/bin/bash
	install $(DEBIAN_DIR)/local/faketrue $(DEBIAN_DIR)/busybox/sbin/update-modules
	dh_installinit -n $(DEBHELPER_PACKAGES_DEB)
	#dh_installdocs $(DEBHELPER_PACKAGES_DEB)
	#dh_installchangelogs Changelog $(DEBHELPER_PACKAGES_DEB)
	dh_strip $(DEBHELPER_PACKAGES_DEB)
	dh_link $(DEBHELPER_PACKAGES_DEB)
	dh_compress $(DEBHELPER_PACKAGES_DEB)
	dh_fixperms $(DEBHELPER_PACKAGES_DEB)
	dh_installdeb $(DEBHELPER_PACKAGES_DEB)
	dh_shlibdeps $(DEBHELPER_PACKAGES_DEB)
	dh_gencontrol
	dh_md5sums
	dh_builddeb

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