#!/usr/bin/make -f
# Sample debian/rules that uses debhelper.
# GNU copyright 1997 to 1999 by Joey Hess.

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

DEB_HOST_ARCH_CPU := $(shell dpkg-architecture -qDEB_HOST_ARCH_CPU)

ifeq ($(DEB_HOST_ARCH_CPU), mipsel)
kfreebsd_cpu	:= mips
else
kfreebsd_cpu	:= $(DEB_HOST_ARCH_CPU)
endif

major=8
minor=2

HEADERS_PACKAGE	:= $(CURDIR)/debian/kfreebsd-kernel-headers
SRC_TAR		:= /usr/src/kfreebsd-source-$(major).$(minor).tar.xz

clean:
	dh_testdir
	dh_testroot
	rm -rf .pc
	rm -f *-stamp
	rm -rf sys usr.sbin linux
	dh_clean

.PHONY: clean

build-indep:

build-arch: build-arch-stamp
build-arch-stamp:
	dh_testdir

	tar xfJ $(SRC_TAR) --wildcards --strip-components=1 "*.h"

	set -e ; \
	fbsd_version=$$(sed sys/sys/param.h -ne "s/^#\s*define\s\+__FreeBSD_version\s\+\([0-9]*\)\s.*/\1/p") ; \
	find sys -type f | (while read i ; do \
	sed -i $$i \
		-e 's/defined\s*(\s*__FreeBSD__\s*)/1/g' \
		-e 's/#\s*ifdef\s*__FreeBSD__\(\s\|$$\)/#if 1/g' \
		-e 's/#\s*ifndef\s*__FreeBSD__\(\s\|$$\)/#if 0/g' \
		-e 's/__FreeBSD__/$(major)/g' \
		\
		-e "s/__FreeBSD_version/$$fbsd_version/g" \
	; done)

	QUILT_PATCHES=$(CURDIR)/debian/patches quilt push -a || test $$? = 2

	touch $@

build: build-indep build-arch

.PHONY: build-indep build-arch build

install-indep: build-indep

install-arch: build-arch
	dh_testdir
	dh_testroot
	dh_prep
	dh_installdirs
	dh_install --sourcedir=$(CURDIR)

ifneq ($(filter i386 amd64, $(kfreebsd_cpu)),)
	sh debian/generate-asm.sh $(kfreebsd_cpu) $(CURDIR)/sys $(HEADERS_PACKAGE)/usr/include
else
	mkdir -p $(HEADERS_PACKAGE)/usr/include/machine
	cd $(CURDIR)/sys/$(kfreebsd_cpu)/include \
		&& find . -type f -name "*.h" -exec cp --parents {} $(HEADERS_PACKAGE)/usr/include/machine \;
endif

install: install-indep install-arch

.PHONY: install-indep install-arch install

# Build architecture-independent files here.
binary-indep: install-indep
# We have nothing to do by default.

# Build architecture-dependent files here.
binary-arch: install-arch
	dh_testdir
	dh_testroot
	dh_installdocs
#	dh_installman
	dh_installchangelogs
	dh_link
	dh_strip
	dh_compress
	dh_fixperms
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary: binary-indep binary-arch

.PHONY: binary-indep binary-arch binary
