#!/usr/bin/make -f

ifeq (,$(filter terse,${DEB_BUILD_OPTIONS}))
export DH_VERBOSE=1
export V=1
export VERBOSE=1
endif

LC_ALL:=C
export LC_ALL

shellescape='$(subst ','\'',$(1))'
shellexport=$(1)=$(call shellescape,${$(1)})

ifneq (,$(wildcard /usr/share/dpkg/buildtools.mk))
include /usr/share/dpkg/buildtools.mk
else
# is ${CC} defined anywhere (other than implicit rules?)
ifneq (,$(findstring $(origin CC),default undefined))
# no - then default to gcc (or cross-gcc)
DEB_BUILD_ARCH?=$(shell dpkg-architecture -qDEB_BUILD_ARCH)
DEB_HOST_ARCH?=$(shell dpkg-architecture -qDEB_HOST_ARCH)
ifneq (${DEB_BUILD_ARCH},${DEB_HOST_ARCH})
DEB_HOST_GNU_TYPE?=$(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
CC=		${DEB_HOST_GNU_TYPE}-gcc
AR=		${DEB_HOST_GNU_TYPE}-ar
RANLIB=		${DEB_HOST_GNU_TYPE}-ranlib
else
CC=		gcc
AR=		ar
RANLIB=		ranlib
endif
endif
endif

OUR_CPPFLAGS:=
OUR_CFLAGS:=
OUR_LDFLAGS:=	-Wl,--as-needed

ifneq (,$(filter debug,${DEB_BUILD_OPTIONS}))
OUR_CFLAGS+=	-Og -g3
endif

OUR_CFLAGS+=	-Wall -Wextra -Wformat
OUR_CPPFLAGS+=	-DNEED_STRTONUM
OUR_CPPFLAGS+=	-I. -DMBSDPORT_H=\"rs.h\"

ifneq (,$(wildcard /usr/share/dpkg/buildflags.mk))
# dpkg-dev (>= 1.16.1~)
dpkgbuildflagsmkescape=$(subst \,\\\,$(1))
export DEB_BUILD_MAINT_OPTIONS:=hardening=+all
export DEB_CPPFLAGS_MAINT_APPEND:=$(call dpkgbuildflagsmkescape,${OUR_CPPFLAGS})
export DEB_CFLAGS_MAINT_APPEND:=$(call dpkgbuildflagsmkescape,${OUR_CFLAGS})
export DEB_LDFLAGS_MAINT_APPEND:=$(call dpkgbuildflagsmkescape,${OUR_LDFLAGS})
include /usr/share/dpkg/buildflags.mk
else
# old-fashioned way to determine build flags
CFLAGS=		-O$(if $(findstring noopt,${DEB_BUILD_OPTIONS}),0,2) -g
CPPFLAGS+=	${OUR_CPPFLAGS}
CFLAGS+=	${OUR_CFLAGS} -std=gnu99
LDFLAGS+=	${OUR_LDFLAGS}
endif

#include /usr/share/dpkg/pkg-info.mk

#ifneq (,$(filter parallel,${DEB_BUILD_OPTIONS}))
#MAKE_ARGS+=	-j
#else ifneq (,$(filter parallel=%,${DEB_BUILD_OPTIONS}))
#MAKE_ARGS+=	-j$(patsubst parallel=%,%,$(filter parallel=%,${DEB_BUILD_OPTIONS}))
#endif

%:
	dh $@ -Snone

execute_before_dh_auto_clean:
	-rm -f *.o librs.a rs

override_dh_auto_build:
	dh_testdir
	-rm -f *.o librs.a rs
	${CC} ${CPPFLAGS} ${CFLAGS} -c -o rs.o rs.c
	${CC} ${CPPFLAGS} ${CFLAGS} -c -o utf8.o utf8.c
	${CC} ${CPPFLAGS} ${CFLAGS} -c -o strtonum.o .linked/strtonum.c
	${AR} rc librs.a utf8.o strtonum.o
	${RANLIB} librs.a
	${CC} ${CPPFLAGS} ${CFLAGS} ${LDFLAGS} -o rs rs.o -L. -lrs ${LDADD}
	test -x rs

override_dh_auto_test:
	zcat /usr/share/doc/mksh/check.pl.gz | \
	    perl - -s check.t -v -p ./rs