CXX ?= g++
ALSA_SRC_NAME ?= AlsaDevice

# path #
SRC_PATH = src
BUILD_PATH = build

# executable # 
LIB_NAME = libdep_audio.a

# extensions #
SRC_EXT = cpp

SOURCES = $(shell find $(SRC_PATH) -name '*.$(SRC_EXT)' | sort -k 1nr | cut -f2-)
OBJECTS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(BUILD_PATH)/%.o)
DEPS = $(OBJECTS:.o=.d)

# flags #
COMPILE_FLAGS = -Wno-error=nonnull -fPIC -Wall -Werror -Wno-error=unknown-pragmas -Wno-error=unused-function -Wno-error=strict-aliasing -O2 -g -DNDEBUG -fPIC   -std=gnu++11
INCLUDES = -I include

ifneq (on, $(ALSA))
SOURCES := $(filter-out src/$(ALSA_SRC_NAME).cpp,$(SOURCES))
OBJECTS := $(filter-out build/$(ALSA_SRC_NAME).o,$(OBJECTS))
DEP := $(filter-out build/$(ALSA_SRC_NAME).d,$(DEPS))
else
INCLUDES := $(INCLUDES) -I$(ALSA_INSTALL_PATH)/include 
endif

.PHONY: default_target
default_target: release

.PHONY: release
release: export CXXFLAGS := $(CXXFLAGS) $(COMPILE_FLAGS)
release: dirs
	@$(MAKE) all

.PHONY: dirs
dirs:
	@echo "Creating directories"
	@mkdir -p $(dir $(OBJECTS))

.PHONY: clean
clean:
	@$(RM) -r $(BUILD_PATH)
	@$(RM) -r $(LIB_NAME)

# checks the executable and symlinks to the output
.PHONY: all
all: $(LIB_NAME)

# Creation of the executable
$(LIB_NAME): $(OBJECTS)
	ar -r $(LIB_NAME) $(OBJECTS)

# Source file rules
# After the first compilation they will be joined with the rules from the
# dependency files to provide header dependencies
$(BUILD_PATH)/%.o: $(SRC_PATH)/%.$(SRC_EXT)
	@echo "Compiling: $< -> $@"
	$(CXX) $(CXXFLAGS) $(INCLUDES) -MP -MMD -c $< -o $@
