#!/usr/bin/make -f

SHELL := sh -e
DEB_HOST_ARCH_OS := $(shell dpkg-architecture -qDEB_HOST_ARCH_OS)
DEB_HOST_GNU_TYPE := $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE := $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
PKGVERSION := $(shell dpkg-parsechangelog | sed -ne 's,^Version: *\(.*\)$$,\1,p')
VENDOR := $(shell dpkg-vendor --query vendor)

ifneq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
RUN_TESTSUITE = y
endif
TESTSUITE_ENV = SKIP_KNOWN_BUGS=y VERBOSE=y
# always run tests in UTF8 mode to verify unicode support
TESTSUITE_ENV += LANG=C.UTF8
#TESTSUITE_ENV += SKIP_INTERNET_TESTS=y

# support parallel build using DEB_BUILD_OPTIONS=parallel=N
ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
  MAKEFLAGS += \
    -j$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
endif

# build directory
b = build

# which flavours to build
flavours = deb static udeb initramfs

ifneq (${DEB_HOST_GNU_TYPE},${DEB_BUILD_GNU_TYPE})
export CROSS_COMPILE = ${DEB_HOST_GNU_TYPE}-
endif

# we filter out -Werror=format-security from CFLAGS, because
# bb uses constructs like
#  bb_error_msg_and_die(bb_msg_memory_exhausted);
# in many places, and for these, gcc with -Werror=format-security
# will complain, since bb_msg_memory_exhausted is an extern.
EXTRA_CFLAGS = \
 $(filter-out -Werror=format-security, $(shell dpkg-buildflags --get CFLAGS))
EXTRA_LDFLAGS = $(shell dpkg-buildflags --get LDFLAGS)
EXTRA_CPPFLAGS = $(shell dpkg-buildflags --get CPPFLAGS)

${b}/test754813.stamp:
	mkdir -p ${b}
	@echo "Checking if libc can produce working static binaries"
	echo 'int main(void) { return getpwnam("root") ? 0 : 1; }' > ${b}/test754813.c
	${CC} -static -o ${b}/test754813 ${b}/test754813.c
	@${b}/test754813 || { \
	  echo "E: your libc does not produce working statically linked binaries" >&2 ; \
	  echo "E: glibc-2.19 is known to have this bug: http://bugs.debian.org/754813" >&2 ; \
	  echo "E: and https://sourceware.org/bugzilla/show_bug.cgi?id=17250" >&2 ; \
	  echo "E: please update your libc" >&2 ; \
	  exit 1 ; }
	touch $@

build: build-arch build-indep
build-indep:

${b}/%/.stamp-setup: DIR = ${b}/$*
${b}/%/.stamp-setup: debian/config/pkg/% debian/config/os/${DEB_HOST_ARCH_OS} ${b}/test754813.stamp
	dh_testdir
	rm -rf ${DIR}
	mkdir -p ${DIR}
	cp -a -l $(filter-out debian ${b}, $(wildcard *)) ${DIR}

# Generate the .config file. First variable assignment wins.
# Several steps..

# 1, rm it just in case
	rm -f ${DIR}/.config

# 2, put any arch-specific overrides so they will have higher precedence
# should be empty for linux
	cat debian/config/os/${DEB_HOST_ARCH_OS} > ${DIR}/.config

# 3, on non-linux platform, disable all config symbols
# which select PLATFORM_LINUX.
# Configuration information is stored in source files and in Config.src,
# so we have to generate Config.in files first, -- done by gen_build_files.
	${MAKE} -C ${DIR} gen_build_files
ifneq (linux,${DEB_HOST_ARCH_OS})
	find ${DIR} -name Config.in -exec \
	  awk '$$1 == "config" { conf = $$2 } \
	       $$1 == "select" && $$2 == "PLATFORM_LINUX" \
	       { print "CONFIG_" conf "=n"; }' \
	   {} + \
        | sort -u >> ${DIR}/.config
endif

# 4, use the flavour-specific base config file.
	cat debian/config/pkg/$* >> ${DIR}/.config

# 5, sort out the resulting mess using oldconfig Kbuild machinery
	${MAKE} -C ${DIR} oldconfig

	ln -s .config $@

ifeq (y,${RUN_TESTSUITE})
# we run testsuite only for main flavour
test-dep := ${b}/deb/.stamp-test
else
test-dep :=
endif

build-arch: ${b}/stamp-build
${b}/stamp-build: $(patsubst %,${b}/%/.stamp-build, ${flavours}) ${test-dep}
	touch $@

${b}/%/.stamp-build: DIR = ${b}/$*
${b}/%/.stamp-build: ${b}/%/.stamp-setup
	dh_testdir
	$(MAKE) -C ${DIR} install docs/busybox.1 \
	  SKIP_STRIP=y \
	  BB_EXTRA_VERSION="${VENDOR} ${PKGVERSION}" \
	  CONFIG_EXTRA_CFLAGS='${EXTRA_CFLAGS} ${EXTRA_CPPFLAGS}' \
	  CONFIG_EXTRA_LDFLAGS='${EXTRA_LDFLAGS}'
	ln -sf busybox $@

test: ${b}/stamp-test
${b}/stamp-test: $(patsubst %,${b}/%/.stamp-test, ${flavours})
	touch $@
${b}/%/.stamp-test: DIR = ${b}/$*
${b}/%/.stamp-test: ${b}/%/.stamp-build
	@echo ======== running testsuite in ${DIR} ========
# mdev testsuite requires chroot which does not work as non-root user
	rm -f ${DIR}/testsuite/mdev.tests
# disable or fix some failing tests
	if [ -f debian/testsuite-${DEB_HOST_ARCH_OS}.diff ] && \
	   ! [ -f ${DIR}/.tests-fixed ]; then \
		( cd ${DIR} && patch -p1 && touch .tests-fixed; ) \
		  < debian/testsuite-${DEB_HOST_ARCH_OS}.diff ; \
	fi
	cd ${DIR}/testsuite && ${TESTSUITE_ENV} ./runtest -v
	touch $@

clean:
	dh_testdir
	rm -rf ${b}
	dh_clean

# define $a variable to be one of -i (indep), -a (arch) or nothing (both)
a :=
binary-indep: a := -i
binary-indep: install
binary-arch: a := -a
binary-arch: install
binary: install

install: ${b}/stamp-build
	dh_testroot
	dh_testdir
	dh_prep

	dh_installdocs $a
	dh_installchangelogs $a
	dh_install $a

# busybox
	dh_install -pbusybox ${b}/deb/busybox /bin
	dh_installman -pbusybox ${b}/deb/docs/busybox.1
	dh_installdocs -pbusybox docs/syslog.conf.txt docs/mdev.txt

# busybox-static
	dh_install -pbusybox-static ${b}/static/busybox /bin
	dh_installman -pbusybox-static ${b}/static/docs/busybox.1
	dh_installdocs -pbusybox-static docs/syslog.conf.txt docs/mdev.txt
	dh_installexamples -pbusybox-static examples/mdev* examples/udhcp

# busybox-udeb
	# Remove init link, but init support is still compiled in to be used.
	rm -f ${b}/udeb/_install/sbin/init
	dh_install -pbusybox-udeb ${b}/udeb/_install/* /

# busybox-syslogd
	dh_installinit -pbusybox-syslogd 
	dh_installinit -pbusybox-syslogd --name=busybox-klogd

# busybox-initramfs
	dh_install -pbusybox-initramfs ${b}/initramfs/busybox /usr/lib/initramfs-tools/bin/
	install -D debian/tree/busybox/usr/share/initramfs-tools/hooks/zz-busybox debian/busybox-initramfs/usr/share/initramfs-tools/hooks/zz-busybox-initramfs


ifeq (linux,$(DEB_HOST_ARCH_OS))
# udhcpc
# udhcpd
	dh_installinit -pudhcpd --onlyscripts
endif

# common actions

	dh_strip $a
	dh_link $a
	dh_compress $a
	dh_fixperms $a
	dh_installdeb $a
	dh_shlibdeps $a

# after shlibdeps finished, grab ${shlibs:Depends} from busybox package
# and transform it into Built-Using field (also dpkg-query bug #588505)
	if [ -f debian/busybox.substvars ]; then \
	  pkgs=$$(sed -n -e's/([^)]*)//g' -e's/,//g' -e's/^shlibs:Depends=//p' debian/busybox.substvars); \
	  srcs=; for p in $$pkgs; do \
	    srcs="$$srcs $$(dpkg-query -f '$${source:Package} (= $${source:Version}),' -W $$p)"; \
	  done ; \
	  echo "built-using=$$srcs" >> debian/busybox-static.substvars ; \
	fi

	dh_gencontrol $a
	dh_md5sums $a
	dh_builddeb $a

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

.PRECIOUS: ${b}/%/.stamp-setup ${b}/%/.stamp-build ${b}/%/.stamp-test \
	${b}/stamp-%
