CC      ?= cc
PREFIX  ?= /usr/local
PKGCFG  := $(shell pkg-config --exists ncursesw && echo yes)

CFLAGS  ?= -Os -Wall -Wextra -std=c11 -D_GNU_SOURCE
CPPFLAGS := -Isrc -Ithird_party
LDFLAGS ?=

ifeq ($(PKGCFG),yes)
    CFLAGS  += $(shell pkg-config --cflags ncursesw)
    LDLIBS  += $(shell pkg-config --libs ncursesw)
else
    LDLIBS  += -lncursesw
endif

SRCS := $(wildcard src/*.c) $(wildcard src/ui/*.c) third_party/cJSON.c
OBJS := $(SRCS:.c=.o)
BIN  := transtui

.PHONY: all clean release install install-desktop

all: $(BIN)

$(BIN): $(OBJS)
	$(CC) $(CFLAGS) $(OBJS) -o $@ $(LDFLAGS) $(LDLIBS)

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

release: CFLAGS += -DNDEBUG
release: clean $(BIN)
	strip $(BIN)

install: release
	install -Dm755 $(BIN) $(DESTDIR)$(PREFIX)/bin/$(BIN)
ifeq ($(shell id -u),0)
	@echo "Running as root - skipping desktop/magnet-link registration"
	@echo "(it installs into \$$HOME for the invoking user). Run"
	@echo "'make install-desktop' as your normal user to enable it."
else
	$(MAKE) install-desktop
endif

# Registers transtui as the handler for magnet: links and .torrent files, so
# "Open with" in a browser/file manager routes straight to `transtui --add`
# (see desktop/transtui-add.desktop). Requires transtui already on PATH
# (run `make install` first) and the xdg-utils/desktop-file-utils tools.
install-desktop:
	install -Dm644 desktop/transtui-add.desktop \
		$(DESTDIR)$(HOME)/.local/share/applications/transtui-add.desktop
	-update-desktop-database $(DESTDIR)$(HOME)/.local/share/applications 2>/dev/null
	-xdg-mime default transtui-add.desktop x-scheme-handler/magnet
	-xdg-mime default transtui-add.desktop application/x-bittorrent

clean:
	rm -f $(OBJS) $(BIN)
