# Metadata about this makefile and position
MKFILE_PATH := $(lastword $(MAKEFILE_LIST))
CURRENT_DIR := $(patsubst %/,%,$(dir $(realpath $(MKFILE_PATH))))

GO_VERSION ?= 1.12.4
XGO_BASE_IMAGE ?= cssx/xgo-${GO_VERSION}

# Current system information
GOOS ?= $(shell go env GOOS)
GOARCH ?= $(shell go env GOARCH)

# Default os-arch combination to build
XC_OS ?= darwin linux windows
XC_ARCH ?= 386 amd64
XC_EXCLUDE ?= darwin/386 linux/386

# External linkers for Windows (to get a static exe with libltdl included)
WINDOWS_EXTLD_amd64 = x86_64-w64-mingw32-gcc
WINDOWS_EXTLD_386 = i686-w64-mingw32-gcc
WINDOWS_API_LEVEL = 5.1
LIBTOOL_PATH = https://mirrors.kernel.org/gnu/libtool/libtool-2.4.6.tar.gz

PROJECT := $(CURRENT_DIR:$(GOPATH)/src/%=%)
NAME := $(notdir $(PROJECT))
GIT_COMMIT ?= $(shell git rev-parse --short HEAD)
VERSION ?= $(shell git describe --always)
LD_FLAGS := -X main.version=${VERSION}

# Create a cross-compile target for every os-arch pairing. This will generate
# a make target for each os/arch like "make linux/amd64" as well as generate a
# meta target (build) for compiling everything.
define make-xc-target
  $1/$2:
  ifneq (,$(findstring ${1}/${2},$(XC_EXCLUDE)))
		@printf "%s%20s %s\n" "-->" "${1}/${2}:" "${PROJECT} (excluded)"
  else ifeq (${1},windows)
		@printf "%s%20s %s\n" "-->" "${1}/${2}:" "${PROJECT} (-w -extldflags "-static" -extld ${WINDOWS_EXTLD_${2}})"
		@xgo -go ${GO_VERSION} -image ${XGO_BASE_IMAGE} -deps ${LIBTOOL_PATH} -targets '${1}-${WINDOWS_API_LEVEL}/${2}' \
			-ldflags '${LD_FLAGS} -w -extldflags "-static" -extld ${WINDOWS_EXTLD_${2}}' .
		@mv ghostunnel-${1}-${WINDOWS_API_LEVEL}-${2}.exe dist/ghostunnel-${VERSION}-${1}-${2}-with-pkcs11.exe
  else
		@printf "%s%20s %s\n" "-->" "${1}/${2}:" "${PROJECT}"
		@xgo -go ${GO_VERSION} -image ${XGO_BASE_IMAGE} -deps ${LIBTOOL_PATH} -ldflags "${LD_FLAGS}" -targets '${1}/${2}' .
		@mv ghostunnel-${1}*-${2} dist/ghostunnel-${VERSION}-${1}-${2}-with-pkcs11
  endif
  .PHONY: $1/$2

  $1:: $1/$2
  .PHONY: $1

  build:: $1/$2
  .PHONY: build
endef
$(foreach goarch,$(XC_ARCH),$(foreach goos,$(XC_OS),$(eval $(call make-xc-target,$(goos),$(goarch),$(if $(findstring windows,$(goos)),.exe,)))))

# dist builds the binaries for distribution
dist:
	@rm -rf "${CURRENT_DIR}/dist/"
	@mkdir -p "${CURRENT_DIR}/dist/"
	@$(MAKE) -f Makefile ghostunnel.man
	@mv ghostunnel.man "${CURRENT_DIR}/dist/ghostunnel-${VERSION}.man"
	@$(MAKE) -f "${MKFILE_PATH}" -j1 build
.PHONY: dist
