#################
# Configuration #
#################

# Paths
BUILDDIR = build
SRC = src
prefix = /usr/local
bindir = $(prefix)/bin
mandir = $(prefix)/share/man

# Exe
CC = gcc
SED = sed
STRIP = strip
INSTALL = install

# Sources
CSOURCES = $(wildcard $(SRC)/*.c)
OBJECTS = $(CSOURCES:$(SRC)/%.c=$(BUILDDIR)/%.o)
DEP = $(CSOURCES:$(SRC)/%.c=$(BUILDDIR)/%.d)

# Flags
CFLAGS += -D_FILE_OFFSET_BITS=64

ifeq ($(OS), Windows_NT)
BIN = bcrypt.exe
CFLAGS += -Iwin32/include/
LDFLAGS += win32/lib/libz.a
else
BIN = bcrypt
LDFLAGS += -lz
endif

ifeq ($(findstring debug,$(MAKECMDGOALS)), debug)
CFLAGS += -O0 -Wall -g -ggdb
STRIP =
else
CFLAGS += -O3 -Wall
endif

# do a static build
ifeq ($(findstring static,$(MAKECMDGOALS)), static)
LDFLAGS += -static
endif

.SUFFIXES: .c .o .d
.PHONY: clean

#####################
# Buid instructions #
#####################

# Build sequence
all: $(BIN)

static: all
debug: all

# Rules to build *.c dependencies
$(BUILDDIR)/%.d: $(SRC)/%.c
	@echo "Calculating $< dependencies"
	@$(CC) -MM $(CFLAGS) $< | $(SED) "s,\($*\).o[ :],$(BUILDDIR)/\1.o $@ : ,g" > $@

# Rules to build *.c
$(BUILDDIR)/%.o: $(SRC)/%.c
	@echo "CC $<"
	@$(CC) -c $(CFLAGS) -o $@ $<

$(BIN): $(DEP) $(OBJECTS)
	@echo "Linking $(BIN)"
	@$(CC) -o $(BIN) $(OBJECTS) $(LDFLAGS)
ifneq ($(STRIP), )
	@echo "Stripping $(BIN)"
	@$(STRIP) $(BIN)
endif

# Include dependencies
ifneq ($(findstring clean,$(MAKECMDGOALS)), clean)
-include $(DEP)
endif

###########
# Install #
###########

install: $(BIN)
	$(INSTALL) -m 755 -o root -g root -d $(bindir)
	$(INSTALL) -m 755 -o root -g root -d $(mandir)/man1
	$(INSTALL) -m 755 -o root -g root $(BIN) $(bindir)/$(BIN)
	$(INSTALL) -m 644 -o root -g root bcrypt.1 $(mandir)/man1/bcrypt.1

#########
# Clean #
#########

clean:
	@echo "Cleaning directory"
	@rm -f $(BIN)
	@rm -f $(DEP)
	@rm -f $(OBJECTS)

