OBJS := $(patsubst %.cpp,%.o,$(wildcard src/*.cpp src/hqx/*.cpp))

DESTDIR = 
PREFIX  = /usr/local
DATADIR = $(PREFIX)/share
BINDIR  = $(PREFIX)/bin
ICONDIR  = $(DATADIR)/pixmaps
APPDIR  = $(DATADIR)/applications

CXX = g++

CXXFLAGS = -Wall -std=c++98 -pedantic `sdl-config --cflags` -pipe
all   : CXXFLAGS += -O2 -s -DNDEBUG -fno-threadsafe-statics -march=native -fomit-frame-pointer -ffast-math -fno-exceptions -fno-rtti
debug : CXXFLAGS += -O0 -g

LDFLAGS = `sdl-config --libs` -lSDL_image -lSDL_net

# lto is supported in g++ version 4.5.0 or higher
CXX_MAJOR := $(shell $(CXX) -dumpversion | cut -d'.' -f1)
CXX_MINOR := $(shell $(CXX) -dumpversion | cut -d'.' -f2)
CXX_LTO := $(shell [ $(CXX_MAJOR) -gt 4 -o \( $(CXX_MAJOR) -eq 4 -a $(CXX_MINOR) -ge 5 \) ] && echo true || echo false)
ifeq ($(CXX_LTO),true)
all : CXXFLAGS += -flto -fwhole-program
endif

EXE = brumbrumrally

all debug: $(EXE)

$(EXE): $(OBJS)
	$(CXX) -o $(EXE) $(OBJS) $(LDFLAGS) $(CXXFLAGS)
	
-include $(OBJS:.o=.d)

%.o: %.cpp
	$(CXX) -c $< -o $@ $(CXXFLAGS)
	@$(CXX) -MM $(CXXFLAGS) $*.cpp > $*.d
	@mv -f $*.d $*.d.tmp
	@sed -e 's|.*:|$*.o:|' < $*.d.tmp > $*.d
	@sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | \
	  sed -e 's/^ *//' -e 's/$$/:/' >> $*.d
	@rm -f $*.d.tmp

clean:
	rm -f $(EXE) src/*.o src/hqx/*.o src/*.d src/hqx/*.d

install: install-exec install-data install-desktop

install-exec: $(EXE)
	install -d $(DESTDIR)$(BINDIR)
	install $(EXE) $(DESTDIR)$(BINDIR)
	-@chmod 755 $(DESTDIR)$(BINDIR)/$(EXE)

install-data:
	install -d $(DESTDIR)$(DATADIR)/$(EXE)
	cp -R data/* $(DESTDIR)$(DATADIR)/$(EXE)

install-desktop:
	install -d $(DESTDIR)$(ICONDIR)
	cp data/images/icon.png $(DESTDIR)$(ICONDIR)/$(EXE).png
	install -d $(DESTDIR)$(APPDIR)
	cp desktop $(DESTDIR)$(APPDIR)/$(EXE).desktop

uninstall: uninstall-exec uninstall-data uninstall-desktop

uninstall-exec:
	rm -f $(DESTDIR)$(BINDIR)/$(EXE)

uninstall-data:
	rm -rf $(DESTDIR)$(DATADIR)/$(EXE)

uninstall-desktop:
	rm -f $(DESTDIR)$(APPDIR)/$(EXE).desktop
	rm -f $(DESTDIR)$(ICONDIR)/$(EXE).png

.PHONY: all debug clean install install-exec install-data install-desktop
