# $Id: makefile,v 1.6 2023/04/08 02:27:01 malakai Exp $
#

EXECUTABLE = searcher

CFILES = searcher.c
ADDITIONAL_HFILES = 
MISSING_HFILES = 

# Debug build options.
# -O2 good for production
# CDEBUG = -O2
# -g -Og good for debugging
CDEBUG = -g -Og
# -Wall for checking code.  See also 'make wall-summary' below.
#CDEBUG += -Wall

CFLAGS = `pkg-config --cflags glib-2.0`
LDFLAGS = 
LINKLIBS = -lm `pkg-config --libs glib-2.0`

# See 'make tar' below.
DATEKEY = `date +%y%m%d%H%M`
TARFILE = ../locolor.$(DATEKEY).tgz

# #### ############################################# ###
# ####         Makefile magic begins here.           ###
# #### Very little needs to change beyond this line! ###
# #### ############################################# ###

CC=gcc
BUILD = ./build

# HFILES generated automatically from CFILES, with additions and exclusions
HFILES := $(ADDITIONAL_HFILES)
HFILES += $(addsuffix .h, $(basename $(CFILES)))
HFILES := $(filter-out $(MISSING_HFILES), $(HFILES))

OFILES = $(CFILES:%.c=$(BUILD)/%.o)

DFILES = $(CFILES:%.c=$(BUILD)/%.d)

RUN = .

# #### Recipies Start Here ####

$(info ---------- START OF COMPILATION -----------)
all : $(BUILD) run tags

# Copying the binaries...
#.PHONY: $(EXECUTABLE)
$(EXECUTABLE) : $(BUILD) $(BUILD)/$(EXECUTABLE)

.PHONY: run
run : $(EXECUTABLE) $(RUN)/$(EXECUTABLE)

# The mv command is to prevent 'text file busy' error, and the 2>/ is some bash
# bullshit to keep the command from failing the make if the source file doesn't
# exist.
$(RUN)/$(EXECUTABLE) : $(BUILD)/$(EXECUTABLE)
	-mv -f $(RUN)/$(EXECUTABLE) $(RUN)/$(EXECUTABLE).prev 2>/dev/null || true
	cp $(BUILD)/$(EXECUTABLE) $(RUN)/$(EXECUTABLE)

# Create build directory...
$(BUILD) : 
	mkdir -p $(BUILD)

# Create run directory...
$(RUN) : 
	mkdir -p $(RUN)

# Linking the binary...
$(BUILD)/$(EXECUTABLE) : $(OFILES)
	$(CC) $(CDEBUG) $(LDFLAGS) $^ -o $(@) $(LINKLIBS)

# check the .h dependency rules in the .d files made by gcc
-include $(DFILES)

# Build the .o's from the .c files, building .d's as you go.
$(BUILD)/%.o : %.c
	$(CC) $(CDEBUG) $(CFLAGS) -MMD -c $< -o $(@)

# Updating the tags file...
tags : $(HFILES) $(CFILES)
	ctags $(HFILES) $(CFILES)

# Cleaning up...
# .PHONY just means 'not really a filename to check for'
.PHONY: clean
clean : 
	-rm $(BUILD)/$(EXECUTABLE) $(RUN)/$(EXECUTABLE).prev $(EXECUTABLE) $(OFILES) $(DFILES) tags
	-rmdir $(BUILD)

.PHONY : tar
tar :
	$(info --- Tar file create ----)
	tar -cvz --exclude-vcs --exclude-from=.exclude --exclude=$(BUILD) -f $(TARFILE) .
	@echo
	@echo ---- Tar File is $(TARFILE) ----

.PHONY: wall-summary
wall-summary: 
	$(info ** Enable these errors in the CDEBUG section to track them down. )
	$(info ** Run this after a make clean for full effect! )
	make "CDEBUG+=-Wall" 2>&1 | egrep -o "\[-W.*\]" | sort | uniq -c | sort -n
	
