CC ?= gcc
CFLAGS = -Wall -Wextra -std=c11 -O2 -g
LDFLAGS = -lpthread -lsqlite3 -lssl -lcrypto

UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
    LDFLAGS += -luuid
    CFLAGS += -D_GNU_SOURCE
endif
ifeq ($(UNAME_S),Darwin)
    CFLAGS += -D_DARWIN_C_SOURCE
endif

INCLUDES = -Iinclude -Isrc

COMMON_SRCS = \
    src/platform/pal.c \
    src/platform/file.c \
    src/platform/time.c \
    src/platform/memory.c \
    src/core/config.c \
    src/core/logging.c \
    src/user/usermgr.c \
    src/user/password.c

SERVER_SRCS = \
    src/main.c \
    src/core/server.c \
    src/http/parser.c \
    src/http/response.c \
    src/http/headers.c \
    src/webdav/xml.c \
    src/webdav/methods.c \
    src/webdav/propfind.c \
    src/webdav/proppatch.c \
    src/webdav/lock.c \
    src/storage/backend.c \
    src/storage/properties.c \
    src/storage/locks.c \
    src/auth/auth.c \
    src/concurrency/threadpool.c \
    src/concurrency/eventloop.c \
    src/concurrency/connpool.c

CLI_SRCS = \
    src/cli/webdavctl.c

COMMON_OBJS = $(COMMON_SRCS:.c=.o)
SERVER_OBJS = $(SERVER_SRCS:.c=.o)
CLI_OBJS = $(CLI_SRCS:.c=.o)

all: nwedav webdavctl

nwedav: $(COMMON_OBJS) $(SERVER_OBJS)
	$(CC) -o $@ $^ $(LDFLAGS)

webdavctl: $(COMMON_OBJS) $(CLI_OBJS)
	$(CC) -o $@ $^ $(LDFLAGS)

%.o: %.c
	$(CC) $(CFLAGS) $(INCLUDES) -c -o $@ $<

clean:
	rm -f $(COMMON_OBJS) $(SERVER_OBJS) $(CLI_OBJS) nwedav webdavctl

install: nwedav webdavctl
	install -d $(DESTDIR)/usr/local/bin
	install -m 755 nwedav $(DESTDIR)/usr/local/bin/
	install -m 755 webdavctl $(DESTDIR)/usr/local/bin/

uninstall:
	rm -f $(DESTDIR)/usr/local/bin/nwedav
	rm -f $(DESTDIR)/usr/local/bin/webdavctl

.PHONY: all clean install uninstall
