dbg = -g
opt =

csrc = $(wildcard src/*.c)
obj = $(csrc:.c=.o)
lib_a = libimago.a

somajor = 2
sominor = 0

incdir = -I$(PREFIX)/include
libdir = -L$(PREFIX)/lib

ifeq ($(shell uname -s), Darwin)
	lib_so = libimago.dylib
	shared = -dynamiclib
	# add macports and fink dirs to the include and lib paths
	incdir += -I/opt/local/include -I/sw/local/include -I/usr/X11R6/include
	libdir += -L/opt/local/lib -L/sw/local/lib -L/usr/X11R6/lib
else
	soname = libimago.so.$(somajor)
	lib_so = $(soname).$(sominor)
	solink = libimago.so
	shared = -shared -Wl,-soname,$(soname)
endif

ifeq ($(shell uname -s), IRIX)
	# add nekoware and SGI freeware dirs to the include and lib paths
	incdir += -I/usr/nekoware/include -I/usr/freeware/include
	libdir += -L/usr/nekoware/lib -L/usr/freeware/lib
endif

CC = gcc
AR = ar
CFLAGS = -pedantic -Wall $(opt) $(dbg) -fPIC -Isrc $(incdir)
LDFLAGS = $(libdir) -lpng -lz -ljpeg -ldl

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

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

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

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

.PHONY: distclean
distclean:
	rm -f $(obj) $(lib_so) $(lib_a) Makefile src/modules.c

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

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