#!/usr/bin/make -f
# -*- makefile -*-
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
DEB_HOST_ARCH_CPU := $(shell dpkg-architecture -qDEB_HOST_ARCH_CPU)
DEB_HOST_ARCH_OS  := $(shell dpkg-architecture -qDEB_HOST_ARCH_OS)

export DEB_BUILD_MAINT_OPTIONS=hardening=+all
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk

ifeq (amd64,$(DEB_HOST_ARCH_CPU))
# PIE disabled on amd64 because it's mostly written in assembly and
# already handles PIC when needed. The codes aren't compiled with
# gcc so enable -fPIE is meaningless.
export DEB_BUILD_MAINT_OPTIONS=hardening=+all,-pie
CFLAGS_NO_PIE := $(shell dpkg-buildflags --get CFLAGS)
LDFLAGS_NO_PIE := $(shell dpkg-buildflags --get LDFLAGS)
endif

LDFLAGS += -Wl,-z,noexecstack

ifeq (arm,$(DEB_HOST_ARCH_CPU))
CFLAGS += -marm
endif

override_dh_auto_build:

	chmod -x app/loc/no

ifeq (amd64,$(DEB_HOST_ARCH_CPU))
	mv src64/tags src64/tags.orig
	make -C src OS=Linux CPU=amd64 picolisp
	make -C src OS=Linux tools gate

	make -C src64 OS=Linux CFLAGS="$(CFLAGS_NO_PIE)" LDFLAGS="$(LDFLAGS_NO_PIE)"
else
	make -C src OS=Linux CPU=$(DEB_HOST_ARCH_CPU) picolisp tools gate
endif
	mkdir -p build/bash_completion.d
	cp lib/bash_completion build/bash_completion.d/pil

#       build time utilities
	-rm src64/sysdeps

override_dh_auto_test:
	HOME=$(CURDIR)/build $(CURDIR)/pil test/lib.l -bye + < /dev/null

override_dh_auto_install:

	dh_install build/bash_completion.d/pil etc/bash_completion.d
	dh_install -X.o src   usr/share/picolisp
	dh_install -X.o src64 usr/share/picolisp

override_dh_auto_clean:

	make -C src clean
	make -C src64 clean
	-rm bin/ssl bin/httpGate bin/lat1 bin/utf2 bin/balance
	-mv src64/tags.orig src64/tags
	-rm -rf build

override_dh_compress:

	dh_compress -X.l

%:
	dh $@ 

VER?=3.0.7.1
get-orig-source:
	rm -rf picolisp-$(VER).orig
	hg clone https://picolisp.googlecode.com/hg/#v$(VER) picolisp-$(VER).orig
	rm -r picolisp-$(VER).orig/.hg picolisp-$(VER).orig/.hgtags
	GZIP=--best tar -cz --owner root --group root --mode a+rX \
			-f picolisp_$(VER).orig.tar.gz \
			picolisp-$(VER).orig
	rm -r picolisp-$(VER).orig
