objify = $(patsubst %.c,obj/%.$2,$(patsubst %.s,obj/%.$2,$1))

CC=clang
INC = -Iext/libtomcrypt/src/headers
CFLAGS  = -std=c99 -D_GNU_SOURCE
CFLAGS += -Wextra -Wall -Werror -Wno-missing-braces -Wno-missing-field-initializers $(INC)
LDFLAGS = -Lext/libtomcrypt -ltomcrypt
DIRS=bin obj out
OBJS = $(call objify,$(SRC),o)

# Enable for testing only
DEBUG=1

ifeq ($(DEBUG), 1)
	CFLAGS += -g -O0 -fsanitize=undefined,leak,address
	LDFLAGS += -fsanitize=undefined,leak,address
	CC=clang
else
	CFLAGS += -O2
endif

# source files
SRC = \
	src/crypt.c \
	src/i2c.c \
	src/main.c

all: libtomcrypt bin/main

obj/%.o: %.c
	case $@ in */*) f=$@; mkdir -p $${f%/*} ;; esac
	$(CC) -o $@ -c $< $(CFLAGS)

bin/main: $(OBJS)
	case $@ in */*) f=$@; mkdir -p $${f%/*} ;; esac
	$(CC) -o bin/main $(OBJS) $(LDFLAGS)

clean:
	rm -rf $(DIRS)
	make -C ext/libtomcrypt clean

libtomcrypt:
	make -C ext/libtomcrypt
