src = $(wildcard src/*.c)
obj = $(src:.c=.o)
dep = $(obj:.o=.d)

hdr = metasurf.h

name = metasurf
lib_a = lib$(name).a
somajor = 0
sominor = 1

ifeq ($(shell uname -s), Darwin)
	lib_so = $(name).dylib
	shared = -dynamiclib
else
	devlink = lib$(name).so
	soname = $(devlink).$(somajor)
	lib_so = $(soname).$(sominor)
	shared = -shared -Wl,-soname=$(soname)
	pic = -fPIC
endif

CC = gcc
AR = ar
CFLAGS = -pedantic -Wall $(dbg) $(opt) $(pic)

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

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

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

-include $(dep)

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

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

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

.PHONY: install
install:
	mkdir -p $(PREFIX)/include $(PREFIX)/lib
	cp src/$(hdr) $(PREFIX)/include/$(hdr)
	cp $(lib_so) $(PREFIX)/lib/$(lib_so)
	[ -n "$(soname)" ] \
		&& rm -f $(PREFIX)/lib/$(soname) $(PREFIX)/lib/$(devlink) \
		&& ln -s $(PREFIX)/lib/$(lib_so) $(PREFIX)/lib/$(soname) \
		&& ln -s $(PREFIX)/lib/$(soname) $(PREFIX)/lib/$(devlink) \
		|| true

.PHONY: uninstall
uninstall:
	rm -f $(PREFIX)/include/$(hdr)
	rm -f $(PREFIX)/lib/$(lib_so)
	[ -n "$(soname)" ] \
		&& rm -f $(PREFIX)/lib/$(soname) $(PREFIX)/lib/$(devlink) \
		|| true
