CC      ?= gcc
MOR     ?= mor
ASTYLE  ?= astyle
UNAME_S := $(shell uname -s 2>/dev/null)
CFLAGS  += -Wall -Wextra -O2 -std=c99 -pedantic

ifeq ($(OS),Windows_NT)
	BIN = liveside.exe
	DEPS_TARGET = deps-windows
	DEPS_DIR = thirdparty/deps-windows
	CPPFLAGS += -I$(DEPS_DIR)/win32ports-dirent_h \
	            -I$(DEPS_DIR)/win32ports-getopt_h \
	            -I$(DEPS_DIR)/win32ports-sys_time_h \
	            -I$(DEPS_DIR)/win32ports-unistd_h
	LDLIBS += -lws2_32
else
	BIN = liveside
	DEPS_TARGET = deps
	DEPS_DIR = thirdparty/deps
	CPPFLAGS += -D_POSIX_C_SOURCE=200809L
	ifeq ($(UNAME_S),Darwin)
		CPPFLAGS += -D_DARWIN_C_SOURCE
	endif
	LDLIBS += -lpthread
endif

TINYCTHREAD_DIR = $(DEPS_DIR)/tinycthread
TINYCTHREAD_SRC = $(TINYCTHREAD_DIR)/source/tinycthread.c
CPPFLAGS += -I$(TINYCTHREAD_DIR)/source
PORT_SRCS = ports/ignore/ignore.c

all: deps $(BIN)

deps: requirements.ini
	$(MOR) $(DEPS_TARGET)

client/liveside.js.inc: client/liveside.js
	awk '{ gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); printf "\t\"%s\\n\"\n", $$0 }' client/liveside.js > $@

$(BIN): liveside.c client/liveside.js.inc $(TINYCTHREAD_SRC) $(PORT_SRCS)
	$(CC) $(CPPFLAGS) $(CFLAGS) -o $@ liveside.c $(TINYCTHREAD_SRC) $(PORT_SRCS) $(LDLIBS)

format:
	@command -v $(ASTYLE) >/dev/null 2>&1 || \
		{ echo "missing astyle; install Artistic Style to format C code"; exit 1; }
	$(ASTYLE) --options=.astylerc liveside.c ports/frankensocket/*.h ports/ignore/*.c ports/ignore/*.h ports/win32/*.h

check-format:
	@command -v $(ASTYLE) >/dev/null 2>&1 || \
		{ echo "missing astyle; install Artistic Style to check C code"; exit 1; }
	@tmp=$$(mktemp -d); \
		for f in liveside.c ports/frankensocket/*.h ports/ignore/*.c ports/ignore/*.h ports/win32/*.h; do \
			mkdir -p "$$tmp/$$(dirname $$f)"; cp "$$f" "$$tmp/$$f"; \
		done; \
		$(ASTYLE) --options=.astylerc "$$tmp"/liveside.c "$$tmp"/ports/frankensocket/*.h "$$tmp"/ports/ignore/*.c "$$tmp"/ports/ignore/*.h "$$tmp"/ports/win32/*.h >/dev/null; \
		diff -ru liveside.c "$$tmp"/liveside.c >/dev/null && \
		diff -ru ports/frankensocket "$$tmp"/ports/frankensocket >/dev/null && \
		diff -ru ports/ignore "$$tmp"/ports/ignore >/dev/null && \
		diff -ru ports/win32 "$$tmp"/ports/win32 >/dev/null || \
		{ echo "C sources are not astyle-formatted; run make format"; rm -rf "$$tmp"; exit 1; }; \
		rm -rf "$$tmp"

check-man: liveside.1
	mandoc -T lint -W warning liveside.1

clean:
	-@rm -f liveside liveside.exe client/liveside.js.inc

distclean: clean
	-@rm -rf thirdparty

.PHONY: all deps format check-format check-man clean distclean
