NAME = apiary

.DEFAULT_GOAL := all
.PHONY: all clean

INSTALL_PREFIX ?= /usr/local

VERSION = $(shell cat version.go |grep "Version"| cut -d "=" -f2| tr -d "\" ")
ARCH = $(shell go env | grep GOHOSTARCH | cut -d"=" -f2 | tr -d "\"")
OS = $(shell go env | grep GOHOSTOS | cut -d"=" -f2 | tr -d "\"")
GIT_COMMIT := $(shell git rev-parse --short HEAD)

BUILD_DIR = build/binary/current
BUILD_OUTPUT = $(BUILD_DIR)/$(NAME)-$(VERSION)-$(OS)-$(ARCH)
BUILD_FLAGS = -tags embed -ldflags "-X github.uio.no/torjus/apiary.Build=$(GIT_COMMIT)" -o $(BUILD_OUTPUT)

GEODB_URL = https://raw.githubusercontent.com/geoacumen/geoacumen-country/master/Geoacumen-Country.mmdb
GEODB_PATH = honeypot/Geoacumen-Country.mmdb

FRONTEND_BUILD_DIR = web/frontend/dist

ifeq ($(INSTALL_PREFIX), /)
	INSTALL_BIN_DIR=/usr/bin
	INSTALL_ETC_DIR=/etc/$(NAME)
else
	INSTALL_BIN_DIR=$(INSTALL_PREFIX)/bin
	INSTALL_ETC_DIR=$(INSTALL_PREFIX)/etc/$(NAME)
endif

$(GEODB_PATH):
	curl $(GEODB_URL) -o $(GEODB_PATH)

$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

$(FRONTEND_BUILD_DIR):
	cd web/frontend && yarn install && yarn build

$(BUILD_OUTPUT): $(BUILD_DIR) $(GEODB_PATH) $(FRONTEND_BUILD_DIR)
	CGO_ENABLED=0 go build $(BUILD_FLAGS) cmd/apiary.go

frontend:
	cd web/frontend && yarn install && yarn build

clean:
	rm -rv $(BUILD_DIR)
	rm -rv $(FRONTEND_BUILD_DIR)

geodb: $(GEODB_PATH)

build: $(BUILD_OUTPUT)

install: build
	mkdir -p $(INSTALL_BIN_DIR)
	mkdir -p $(INSTALL_ETC_DIR)
	install -m 755 $(BUILD_OUTPUT) $(INSTALL_BIN_DIR)/$(NAME)
	install -m 755 apiary.toml $(INSTALL_ETC_DIR)/apiary.toml

uninstall:
	rm -v $(INSTALL_ETC_DIR)/apiary.toml
	rmdir -v $(INSTALL_ETC_DIR)
	rm -v $(INSTALL_BIN_DIR)/$(NAME)