# Configure the packages required by your project and its target executable
PKGS 		:= 
TARGET 		:= hello

# Vala-compiler options
VALAC 		:= valac
VALAFLAGS 	:= 

# C-compiler options
CC 		:= gcc
CFLAGS 		:= -O -Wall
PKG_CFLAGS 	:= $(shell pkg-config --cflags gobject-2.0 $(PKGS))
PKG_LIBS 	:= $(shell pkg-config --libs gobject-2.0 $(PKGS))

# Set directories
SRC_DIR 	:= $(DIRECTORY)src
BUILD_DIR 	:= $(DIRECTORY)build
VALA_AUX 	:= $(DIRECTORY).vala-aux

# Locate necessary files
VALAFILES := $(shell find $(SRC_DIR) -type f -name "*.vala")
CFILES = $(BUILD_DIR)/c/$(notdir $(VALAFILES:.vala=.c))
OFILES = $(BUILD_DIR)/o/$(notdir $(CFILES:.c=.o))

# Set stemp and deps information
# This part is needed in order to avoid re-building everything each time
BASENAMES = $(notdir $(basename $(VALAFILES)))
VALA_FASTVAPI_FILES = $(foreach f, $(BASENAMES), $(VALA_AUX)/$(f).vapi)
VALA_FASTVAPI_STAMPS = $(foreach f, $(BASENAMES), $(VALA_AUX)/$(f).vapi.stamp)
VALA_DEPS = $(foreach f, $(BASENAMES), $(VALA_AUX)/$(f).dep)

.PRECIOUS: $(VALA_AUX)/%.vapi.stamp $(VALA_AUX)/%.dep

all: compile target

#$(VALA_FASTVAPI_FILES): ;

$(VALA_FASTVAPI_STAMPS): $(VALAFILES) | $(VALA_AUX)
	@echo '  GEN    '$(@:.stamp=); $(VALAC) --fast-vapi=$(@:.stamp=) $< && touch $@

$(VALA_DEPS): $(VALAFILES) | $(VALA_FASTVAPI_STAMPS)
	@echo '  VALAC  '$(notdir $<); $(VALAC) -C --deps=$@ -b $(SRC_DIR) -d $(BUILD_DIR)/c $(VALAFLAGS) $(addprefix --use-fast-vapi=,$(subst $(VALA_AUX)/$(notdir $(basename $@)).vapi,, $(VALA_FASTVAPI_FILES))) $(addprefix --pkg=,$(PKGS)) $<

$(VALA_AUX):
	@mkdir -p $(VALA_AUX)

$(CFILES) : | $(VALA_DEPS) ;

$(OFILES): $(CFILES)
	@echo '  CC     '$(notdir $<); mkdir -p $(BUILD_DIR)/o; $(CC) -c $(CFLAGS) $(PKG_CFLAGS) -o $@ $<

target: $(OFILES)
	@echo '  Generating executable...'; $(CC) -o $(BUILD_DIR)/$(TARGET) $(OFILES) $(PKG_LIBS)
	@echo '  Done.'

compile: $(VALA_DEPS)

clean:
	@echo '  Cleaning up...'; $(RM) -r $(BUILD_DIR) $(VALA_AUX)

.PHONY: all clean target

include $(wildcard $(VALA_AUX)/*.dep)

