ROOT_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))

src = $(wildcard $(ROOT_DIR)/*.c $(ROOT_DIR)/deps/*.c)
obj = $(src:.c=.o)

PREFIX ?= "/usr/local"

# determine architecture
ARCH ?= $(shell uname -p)

# alpine Linux 32 bit static linking build
ifeq ($(ARCH),i686)
  LDFLAGS = -static
  CFLAGS= -pedantic -Wall -Wformat-security -Wformat -Werror -Os -m32 -std=c99 -fomit-frame-pointer -mtune=generic -msse4.2 -fstack-protector-strong -fPIE -pie
# Ubutun 18.04 Bionic 64 bit build
else
  LDFLAGS = -lm
  CFLAGS= -pedantic -Wall -Wformat-security -Wformat -Werror -Os -m64 -std=c99 -fomit-frame-pointer -mtune=generic -msse4.2 -fstack-protector-strong -fPIE -pie
  CFLAGS+= -D_FORTIFY_SOURCE=2 -fPIC -Wl,-z,relro -Wl,-z,now -Wl,-z,nodlopen -Wl,-z,nodump 
  CFLAGS+= -mfunction-return=thunk -mindirect-branch=thunk
  CFLAGS+= -Wformat=2
endif

http_proxy: $(obj)
	$(CC) -o $(ROOT_DIR)/$@ $^ $(CFLAGS) $(LDFLAGS)

.PHONY: install
install: http_proxy
	@echo "Installing binary in $(PREFIX)"
	mkdir -p $(PREFIX)/bin
	install -m 0755 $(ROOT_DIR)/http_proxy $(PREFIX)/bin

.PHONY: clean
clean:
		rm -f $(obj) $(ROOT_DIR)/http_proxy

.PHONY: showarch
showarch:
	@echo "Arch is $(ARCH)"