
obj = src/spnav.o src/proto.o src/util.o $(magellan_obj)
hdr = src/spnav.h src/spnav_magellan.h src/spnav_config.h

name = spnav
lib_a = lib$(name).a

incpaths = -I. -I/usr/local/include -I/usr/X11R6/include -I/opt/homebrew/include
libpaths = -L/usr/local/lib -L/usr/X11R6/lib -L/opt/homebrew/lib

CC ?= gcc
AR ?= ar
CFLAGS = $(opt) $(dbg) -std=c89 $(pic) -pedantic -Wall -fno-strict-aliasing $(incpaths) $(user_cflags) `dpkg-buildflags --get CFLAGS` `dpkg-buildflags --get CPPFLAGS`
LDFLAGS = $(libpaths) $(user_ldflags) $(xlib) -lm `dpkg-buildflags --get LDFLAGS`

ifeq ($(shell uname -s), Darwin)
	lib_so = libspnav.dylib
	shared = -dynamiclib
else
	so_major = 0
	so_minor = 4
	devlink = lib$(name).so
	soname = $(devlink).$(so_major)
	lib_so = $(soname).$(so_minor)
	shared = -shared -Wl,-soname,$(soname)
	pic = -fPIC
endif


.PHONY: all
all: $(lib_a) $(lib_so)

$(lib_a): $(obj)
	$(AR) rcs $@ $(obj)

$(lib_so): $(obj)
	$(CC) $(shared) -o $@ $(obj) $(LDFLAGS)

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

.PHONY: clean
clean:
	rm -f $(obj)

.PHONY: distclean
distclean:
	rm -f $(obj) $(lib_a) $(lib_so) Makefile

.PHONY: install
install: $(lib_a) $(lib_so) $(hdr)
	mkdir -p $(DESTDIR)$(PREFIX)/$(libdir) $(DESTDIR)$(PREFIX)/include
	cp $(lib_a) $(DESTDIR)$(PREFIX)/$(libdir)/$(lib_a)
	cp $(lib_so) $(DESTDIR)$(PREFIX)/$(libdir)/$(lib_so)
	[ -n "$(soname)" ] && \
		rm -f $(DESTDIR)$(PREFIX)/$(libdir)/$(soname) $(DESTDIR)$(PREFIX)/$(libdir)/$(devlink) && \
		cd $(DESTDIR)$(PREFIX)/$(libdir) && \
		ln -s $(lib_so) $(DESTDIR)$(PREFIX)/$(libdir)/$(soname) && \
		ln -s $(soname) $(DESTDIR)$(PREFIX)/$(libdir)/$(devlink) || \
		true
	for h in $(hdr); do cp -p $(srcdir)/$$h $(DESTDIR)$(PREFIX)/include/; done
	mkdir -p $(DESTDIR)$(PREFIX)/share/pkgconfig
	cp spnav.pc $(DESTDIR)$(PREFIX)/share/pkgconfig/spnav.pc

.PHONY: uninstall
uninstall:
	rm -f $(DESTDIR)$(PREFIX)/$(libdir)/$(lib_a)
	rm -f $(DESTDIR)$(PREFIX)/$(libdir)/$(lib_so)
	[ -n "$(soname)" ] && \
		rm -f $(DESTDIR)$(PREFIX)/$(libdir)/$(soname) $(DESTDIR)$(PREFIX)/$(libdir)/$(devlink) || \
		true
	for i in $(hdr); do rm -f $(DESTDIR)$(PREFIX)/include/$$i; done
	rm -f $(DESTDIR)$(PREFIX)/share/pkgconfig/spnav.pc

.PHONY: examples
examples:
	$(MAKE) -C examples/simple
	$(MAKE) -C examples/cube
	$(MAKE) -C examples/fly
