#!/usr/bin/make -f

DO_SELINUX=0
export DO_SELINUX

IPTABLES = iptables_profectio
KERNEL = kernel_profectio

BUILD_DIR := $(CURDIR)/debian/build
SRC_DIR := $(BUILD_DIR)/$(IPTABLES)
STAMP_DIR := $(BUILD_DIR)/stamp
DOCS_DIR := $(BUILD_DIR)/docs

MANDIR := MANDIR=/usr/share/man
BINDIR := BINDIR=/sbin
LIBDIR := LIBDIR=/lib
DESTDIR := DESTDIR=$(CURDIR)/debian/iptables
#KERNEL_DIR := KERNEL_DIR=$(BUILD_DIR)/$(KERNEL)
KERNEL_DIR := KERNEL_DIR=/usr

BUILD_VARS := $(LIBDIR) $(KERNEL_DIR)
INSTALL_VARS := $(DESTDIR) $(MANDIR) $(LIBDIR) $(BINDIR) $(KERNEL_DIR)
BUILD_TARGETS := all ip6tables-save ip6tables-restore # iptables.8 ip6tables.8 
KEEP_THESE = libipt_IDLETIMER.so libipt_REJECT.so libipt_icmp.so \
	libipt_limit.so libipt_standard.so libipt_tcp.so libipt_udp.so \
	libip6t_REJECT.so libip6t_icmp6.so libip6t_limit.so libip6t_standard.so \
	libip6t_tcp.so libip6t_udp.so

build_howtos := $(foreach howto,$(wildcard $(CURDIR)/howtos/*.sgml),sgml2html $(howto);) 

manregex := $(SHELL) $(CURDIR)/scripts/manregex
MAN_PAGES := $(SRC_DIR)/*.8 

links: $(STAMP_DIR)/links
$(STAMP_DIR)/links:
	-mkdir -p $(STAMP_DIR)
	-ln -s /usr/src/rx-34-kernel-headers /usr/src/linux
	touch $@

prep: $(STAMP_DIR)/prep
$(STAMP_DIR)/prep:
	install -d $(STAMP_DIR)
	cp -a iptables $(BUILD_DIR)/$(IPTABLES)
	cp -a linux $(BUILD_DIR)/$(KERNEL)
	touch $@

howtos: $(STAMP_DIR)/howtos
$(STAMP_DIR)/howtos:
	install -d $(DOCS_DIR)
	cd $(DOCS_DIR); $(build_howtos)
	touch $@

build: links prep
	dh_testdir

	$(MAKE) -C $(SRC_DIR) $(BUILD_TARGETS) $(BUILD_VARS)

	#$(manregex) $(MAN_PAGES) 

	cd $(SRC_DIR); ar rcs libiptables.a iptables.o
	cd $(SRC_DIR); ar rcs libip6tables.a ip6tables.o

clean:
	dh_testdir
	rm -rf $(BUILD_DIR)
	dh_clean

install: build
	dh_testdir
	dh_testroot

	$(MAKE) -C $(SRC_DIR) install $(INSTALL_VARS)

	# Remove the modules we do not need
	-for i in `ls $(CURDIR)/debian/iptables/lib/iptables/*.so`; \
	do \
		keep=0; \
		BASENAME=`basename $$i`; \
		for j in $(KEEP_THESE); \
		do \
			if [ "$$j" = "$$BASENAME" ]; then \
				keep=1; \
				echo "keeping $$i"; \
				break; \
			fi; \
		done; \
		if [ "$$keep" != "1" ]; then \
			echo "removing $$i"; \
			rm -f $$i; \
		fi; \
	done

	#install -m0644 -D $(CURDIR)/debian/iptables.lintian \
	#	$(CURDIR)/debian/iptables/usr/share/lintian/overrides/iptables


binary-indep: build install

binary-arch: build install
	dh_testdir
	dh_testroot
	dh_install
	#dh_installdocs
	dh_installchangelogs
	dh_strip
	dh_compress
	dh_fixperms
	dh_shlibdeps -X.so
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb

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