# SPDX-License-Identifier: GPL-3.0-or-later
#
#          Author: Erick Gallesio [eg@stklos.net]
#    Creation date: 17-Jul-2024 18:43


#  General variables which depends of the choices made when configure was run
# (compiler used, global compilation flags, ...)
BASEDIR=../..
CC=@CC@
CFLAGS=@CFLAGS@
CPPFLAGS=@CPPFLAGS@
LD=@SH_LOADER@
LDFLAGS=@LDFLAGS@
SH_COMP_FLAGS=@SH_COMP_FLAGS@
SH_LOADER=@SH_LOADER@
SH_LOAD_FLAGS=@SH_LOAD_FLAGS@
SO=@SH_SUFFIX@
STKCFLAGS=@STKCFLAGS@
GCINC=@GCINC@

# ----------------------------------------------------------------------------

# STKLOS_SRC is the directory with the C source of STklos.
# Since this example is in 'examples/c-module', then the
# 'src' subdir is this:
STKLOS_SRC=../../src/

# Same thing with the utils and lib directories
STKLOS_UTILS=../../utils
STKLOS_LIBS=../../lib

# STKLOS_COMPILE is the command used to compile a Scheme file. The command is
# a bit complex here because we want to be able to compile the files in this
# directory without a prior installation of STklos. If you have already
# installed STklos on your machine , you can use the second (commented)
# definition of this variable
STKLOS_COMPILE=$(STKLOS_SRC)/stklos -c -q -I $(STKLOS_LIBS) \
		$(STKLOS_UTILS)/stklos-compile
# STKLOS_COMPILE=stklos-compile

# The following variables are:
# SCHEME_SOURCE -- the Scheme part of the module
# C_INCL        -- C file to be included (generated by stklos-compile)
# C_SOURCE      -- C module source, written by the user
# C_OBJ         -- C object file (intermediate)
# SHARED_OBJ    -- C shared object (loadable library)

SCHEME_SOURCE=string-obfuscate.stk
C_INCL=string-obfuscate-incl.c
C_SOURCE=string-obfuscate.c
C_OBJ=string-obfuscate.o
SHARED_OBJ=string-obfuscate.$(SO)

all: $(SHARED_OBJ)

# We first compile the Scheme file string-obfuscate.stk into a C file
# string-obfuscate-incl.c, so it will be included in the library C file
# later:
string-obfuscate-incl.c: $(SCHEME_SOURCE)
	$(STKLOS_COMPILE) --no-time \
		-C \
		--output=$(C_INCL) \
		$(SCHEME_SOURCE)

# Now we compile the C library, which will include string-obfuscate-incl.c.
string-obfuscate.o: $(C_SOURCE) $(C_INCL)
	$(CC) $(CFLAGS) $(CPPFLAGS) $(STKCFLAGS) $(SH_COMP_FLAGS) \
		$(GCINC) -I$(STKLOS_SRC) \
		-c \
		-o $(C_OBJ) \
		$(C_SOURCE)

# And finally, we make it a shared library so STklos will be able to load it:
string-obfuscate.so: $(C_OBJ)
	$(LD) $(LDFLAGS) $(SH_LOAD_FLAGS) -o $(SHARED_OBJ) $(C_OBJ)

# Install is a noop for this directory
install:

clean:
	rm -f $(C_INCL) $(C_OBJ) $(SHARED_OBJ)

distclean: clean
	rm -f Makefile
