src = $(wildcard src/*.c)
obj = $(src:.c=.o)
dep = $(obj:.o=.d)
name = goatvr
so_major = 0
so_minor = 1

ifdef use_libovr
	mod_cflags += -DUSE_LIBOVR
	mod_libs += -lovr
endif
ifdef use_openhmd
	mod_cflags += -DUSE_OPENHMD
	mod_libs += -lopenhmd
endif

CFLAGS = -pedantic -Wall $(dbg) $(opt) $(pic) $(mod_cflags)
LDFLAGS = $(mod_libs) $(libgl)

lib_a = lib$(name).a
ifeq ($(shell uname -s), Darwin)
	lib_so = lib$(name).dylib
	shared = -dynamiclib
	libgl = -framework OpenGL

	ifdef use_libovr
		mod_libs += -framework Cocoa -framework IOKit
	endif
else
	ldname = lib$(name).so
	soname = lib$(name).so.$(so_major)
	lib_so = lib$(name).so.$(so_major).$(so_minor)
	shared = -shared -Wl,-soname=$(soname)
	pic = -fPIC
	libgl = -lGL -lGLU
endif

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

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

$(soname): $(lib_so)
	ln -sf $< $@

$(ldname): $(soname)
	ln -sf $< $@

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

-include $(dep)

%.d: %.c
	@$(CPP) $(CFLAGS) $< -MM -MT $(@:.d=.o) >$@

.PHONY: clean
clean:
	rm -f $(obj) $(lib_so) $(lib_a) $(soname) $(ldname)

.PHONY: cleandep
cleandep: clean
	rm -f $(dep)

.PHONY: install
install: $(lib_so) $(lib_a)
	mkdir -p $(DESTDIR)$(PREFIX)/include $(DESTDIR)$(PREFIX)/lib
	cp src/vr.h $(DESTDIR)$(PREFIX)/include/goatvr.h
	cp $(lib_a) $(DESTDIR)$(PREFIX)/lib/$(lib_a)
	cp $(lib_so) $(DESTDIR)$(PREFIX)/lib/$(lib_so)
	[ -n "$(soname)" ] && \
		cd $(DESTDIR)$(PREFIX)/lib && \
		ln -s $(lib_so) $(soname) && \
		ln -s $(soname) $(ldname) || \
		true

.PHONY: uninstall
uninstall:
	rm -f $(DESTDIR)$(PREFIX)/include/goatvr.h
	rm -f $(DESTDIR)$(PREFIX)/lib/$(lib_a)
	rm -f $(DESTDIR)$(PREFIX)/lib/$(lib_so)
	[ -n "$(soname)" ] && \
		rm -f $(DESTDIR)$(PREFIX)/lib/$(soname) && \
		rm -f $(DESTDIR)$(PREFIX)/lib/$(ldname) || \
		true
