srcdir = @srcdir@
VPATH  = @srcdir@

include ../../Mk/macports.autoconf.mk

OBJS= 		libmachista.o hashmap.o machista_wrap.o
SHLIB_NAME= machista${SHLIB_SUFFIX}
INSTALLDIR=	${TCL_PACKAGE_PATH}/machista1.0

CPPFLAGS+= -I$(srcdir)/../compat
ifneq ($(HAVE_STRLCAT),yes)
OBJS+= ../compat/strlcat.o
endif

SWIG         = @SWIG@
SWIG_FLAGS   = -tcl8 -pkgversion 1.0 -namespace
SWIG_LDFLAGS = -ltcl

SWIG_IFACE = machista.i
SWIG_SRCS  = ${SWIG_IFACE:%.i=%_wrap.c}
SWIG_OBJS  = ${SWIG_SRCS:%.c=%.o}

TESTS = ./tests/libmachista-test

include $(srcdir)/../../Mk/macports.tea.mk

CFLAGS+= -fPIC
ifeq (darwin,@OS_PLATFORM@)
SHLIB_LDFLAGS+= -install_name ${INSTALLDIR}/${SHLIB_NAME}
endif

${SWIG_SRCS}:: ${SWIG_IFACE}
ifdef SWIG
	${SWIG} ${SWIG_FLAGS} $<
else
	@echo "Building ${SWIG_SRCS} requires swig, which you apparently did not have installed when configuring MacPorts." >&2
	@echo "Please install swig and re-run configure" >&2
	@echo "To use this SWIG, run configure as follows:" >&2
	@echo "    SWIG=/opt/swig/bin/swig ./configure --your-usual-config-flags" >&2
	@echo "If you checked out from git you can also run git restore in base/src/machista1.0 to get rid of this error" >&2
	@exit 1
endif

${SWIG_OBJS}:: ${SWIG_SRCS}

${PKG_INDEX}:: ${SWIG_SHLIB}
	$(SILENT) ../pkg_mkindex.sh $< || ( rm -rf $@ && exit 1 )

clean::
	rm -f ${SWIG_OBJS} ${PKG_INDEX}
	rm -f ${TESTS} \
		tests/libmachista-test-dependency${SHLIB_SUFFIX} \
		tests/libmachista-test-lib${SHLIB_SUFFIX}
	rm -rf ${TESTS:%=%.dSYM} \
		tests/libmachista-test-dependency${SHLIB_SUFFIX}.dSYM \
		tests/libmachista-test-lib${SHLIB_SUFFIX}.dSYM

distclean::
	rm -f Makefile

test:: ${TESTS}
	${TESTS}

tests/libmachista-test: tests/libmachista-test.c libmachista.h libmachista.o hashmap.o tests/libmachista-test-lib${SHLIB_SUFFIX}
	$(CC) $(CFLAGS) -D_POSIX_SOURCE -o $@ -I. $< libmachista.o hashmap.o

# The tests for this library need a universal lib; we used to just use
# /usr/lib/libSystem.B.dylib, but Apple has removed that with macOS 11, so now
# we need a different alternative.
#
# Build a library that's dual arch, relying on $OS_MAJOR to figure out whatever
# dual arch means on the current platform.
#
# The if expression below is basically the equivalent from aclocal.m4 for
# UNIVERSAL_ARCHS, except that we're always forcing some kind of universality.
tests/%${SHLIB_SUFFIX}:
ifeq (darwin,@OS_PLATFORM@)
	${SHLIB_LD} \
		$$(if [ @OS_MAJOR@ -lt 10 ]; then echo "-arch i386 -arch ppc"; elif [ @OS_MAJOR@ -lt 20 ]; then echo "-arch x86_64 -arch i386"; else echo "-arch x86_64 -arch arm64"; fi) \
		-install_name $@ \
		$^ \
		-o $@
else
	touch $@
endif

tests/libmachista-test-dependency${SHLIB_SUFFIX}: tests/empty.c

tests/libmachista-test-lib${SHLIB_SUFFIX}: tests/empty.c tests/libmachista-test-dependency${SHLIB_SUFFIX}

codesign:: $(SHLIB_NAME)
	../codesign.sh $?
