src = $(wildcard src/*.c)
msrc = $(wildcard src/*.m)
obj = $(src:.c=.o) $(msrc:.m=.o)
dep = $(src:.c=.d)
lib_a = libsgl.a
soname = libsgl.so.$(somajor)
lib_so = $(lib_so_$(sys))

somajor = 0
sominor = 0

lib_so_unix = $(soname).$(sominor)
lib_so_mac = libsgl.dylib

sharedopt_unix = -shared -Wl,-soname,$(soname)
sharedopt_mac = -dynamiclib

ifeq ($(shell uname -s), Darwin)
	sys = mac
else
	sys = unix
endif

AR = ar
CC = gcc
CFLAGS = -pedantic -Wall -g -fPIC -Iinclude -Isrc $(wsys_cflags) $(CFLAGS_extra)
LDFLAGS = $(wsys_libs)

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

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

$(lib_so): $(obj)
	$(CC) $(sharedopt_$(sys)) -o $@ $(obj) $(LDFLAGS)

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

-include $(dep)

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

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

.PHONY: install
install:
	mkdir -p $(PREFIX)/include $(PREFIX)/lib
	cp $(lib_a) $(PREFIX)/lib/$(lib_a)
	cp $(lib_so) $(PREFIX)/lib/$(lib_so)
	cp include/sgl.h $(PREFIX)/include/sgl.h

.PHONY: uninstall
uninstall:
	rm -f $(PREFIX)/lib/$(lib_a)
	rm -f $(PREFIX)/lib/$(lib_so)
	rm -f $(PREFIX)/include/sgl.h
