# Written by Arthur Greghi
# 2026 - OpenMountCtl - Licensed under the GPL v3

CC      ?= gcc
PKG_CONFIG ?= pkg-config

PREFIX      ?= /usr
BINDIR       = $(PREFIX)/bin
SYSTEMDDIR   = $(PREFIX)/lib/systemd/system
UDEVDIR      = $(PREFIX)/lib/udev/rules.d
DBUSDIR      = $(PREFIX)/etc/dbus-1/system.d
XDBUSDIR     = $(PREFIX)/share/dbus-1/system-services

CFLAGS  ?= -O2 -Wall -Wextra -Wpedantic
CFLAGS  += $(shell $(PKG_CONFIG) --cflags libudev dbus-1)
LDFLAGS ?=
LDLIBS   = $(shell $(PKG_CONFIG) --libs libudev dbus-1) -lpthread

# Source files for the daemon
SRC := src/main.c        \
       src/utils.c       \
       src/permguard.c   \
       src/mount_handler.c \
       src/udev_watcher.c  \
       src/crypt.c         \
       src/dbus_core.c     \
       src/dbus_service.c  \
       src/dbus_udisks2.c

OBJ := $(SRC:.c=.o)
DEP := $(OBJ:.o=.d)
TARGET := openmountctl

# Declare phony targets
.PHONY: all clean distclean install uninstall

# Build the openmountctl daemon
all: $(TARGET)

$(TARGET): $(OBJ)
	$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)

# Include auto-generated dependency files
-include $(DEP)

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

clean:
	rm -f $(OBJ) $(DEP)

distclean: clean
	rm -f $(TARGET)

# Install binary, systemd unit, udev rules, and dbus configuration
install: $(TARGET) contrib/openmountctl.service \
         contrib/99-openmountctl.rules contrib/org.openmountctl.conf \
         contrib/org.openmountctl.service
	install -d $(DESTDIR)$(BINDIR)
	install -m 755 $(TARGET) $(DESTDIR)$(BINDIR)/openmountctl
	- setcap 'cap_sys_admin,cap_chown,cap_fowner,cap_dac_override+ep' \
	        $(DESTDIR)$(BINDIR)/openmountctl 2>/dev/null; \
	if [ $$? -ne 0 ]; then \
	    echo "  [WARN] setcap failed — run 'sudo setcap ...' or install as root"; \
	fi
	install -d $(DESTDIR)$(SYSTEMDDIR)
	install -m 644 contrib/openmountctl.service $(DESTDIR)$(SYSTEMDDIR)/
	install -d $(DESTDIR)$(UDEVDIR)
	install -m 644 contrib/99-openmountctl.rules $(DESTDIR)$(UDEVDIR)/
	install -d $(DESTDIR)$(DBUSDIR)
	install -m 644 contrib/org.openmountctl.conf $(DESTDIR)$(DBUSDIR)/
	install -d $(DESTDIR)$(XDBUSDIR)
	install -m 644 contrib/org.openmountctl.service $(DESTDIR)$(XDBUSDIR)/
	@echo ""
	@echo "OpenMountCtl installed."
	@echo "Enable the daemon with:  systemctl enable --now openmountctl"

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/openmountctl
	rm -f $(DESTDIR)$(SYSTEMDDIR)/openmountctl.service
	rm -f $(DESTDIR)$(UDEVDIR)/99-openmountctl.rules
	rm -f $(DESTDIR)$(DBUSDIR)/org.openmountctl.conf
	rm -f $(DESTDIR)$(XDBUSDIR)/org.openmountctl.service
	@echo "OpenMountCtl uninstalled."
