#!/usr/bin/make -f

include /usr/share/dpkg/default.mk

################################################################################
# control and install files generation
################################################################################

comma:= ,
empty:=
space:= $(empty) $(empty)

# transform comma separated list to word list
convert_arch_to_deb = $(if $(filter $1,x64),amd64,$1)
convert_arch_to_nodejs = $(if $(filter $1,amd64),x64,$1)

NODEJS_ARCHIVE = node-$(GBP_NODEJS_VERSION)-linux-$(call convert_arch_to_nodejs,$(DEB_HOST_ARCH)).tar.xz

$(NODEJS_ARCHIVE):
	@if [ -n "$(GBP_NODEJS_TOKEN)" ]; then \
	  echo "Downloading $(GBP_NODEJS_URL_BASE)$(GBP_NODEJS_VERSION)/$@"; \
	  STATUS_CODE=$$(curl -s -L -H "Authorization: Bearer $(GBP_NODEJS_TOKEN)" -o $@ -w "%{http_code}" $(GBP_NODEJS_URL_BASE)$(GBP_NODEJS_VERSION)/$@); \
	else \
		STATUS_CODE=$$(curl -s -L -o $@ -w "%{http_code}" $(GBP_NODEJS_URL_BASE)$(GBP_NODEJS_VERSION)/$@); \
	fi; \
	if [ "$${STATUS_CODE}" -eq 404 ] || [ "$${STATUS_CODE}" -eq 401 ]; then \
	  rm -f $@; \
	  echo "Getting $(GBP_NODEJS_URL_BASE)$(GBP_NODEJS_VERSION)/$@ failed: HTTP $${STATUS_CODE}"; \
	  echo "Retry downloading $(GBP_NODEJS_URL_FALLBACK_BASE)$(GBP_NODEJS_VERSION)/$@"; \
	  curl -s -L -o $@ $(GBP_NODEJS_URL_FALLBACK_BASE)$(GBP_NODEJS_VERSION)/$@; \
	else \
	  rm -f $@; \
	  echo "Getting $(GBP_NODEJS_URL_BASE)$(GBP_NODEJS_VERSION)/$@ failed: HTTP $${STATUS_CODE}"; \
	  exit 1; \
	fi

bin/$(DEB_HOST_ARCH)/node: $(NODEJS_ARCHIVE)
	@mkdir -p $(@D)
	@echo "Extracting $@"
	@tar xaf $< -O node-$(GBP_NODEJS_VERSION)-linux-$(call convert_arch_to_nodejs,$(DEB_HOST_ARCH))/bin/node > $@
	@chmod 755 $@

INCDIR := usr/include
$(INCDIR): $(NODEJS_ARCHIVE)
	@rm -rf usr
	@mkdir -p usr
	@echo "Extracting $@"
	@tar -C usr --strip-components=1 -xaf $< node-$(GBP_NODEJS_VERSION)-linux-$(call convert_arch_to_nodejs,$(DEB_HOST_ARCH))/include/
	@find usr/include/node/openssl/archs -mindepth 1 -maxdepth 1 -type d ! -name linux-$$(arch) -exec rm -rf {} +

genfiles: bin/$(DEB_HOST_ARCH)/node | $(INCDIR)
genfiles-cleanup:
	@rm -f $(NODEJS_ARCHIVE)
	@rm -rf bin
	@rm -rf usr

.PHONY: genfiles genfiles-cleanup
################################################################################
# End of control and install files generation
################################################################################

%:
	dh $@

# suppress generation of dbgsym packages
override_dh_strip:
	dh_strip --no-automatic-dbgsym

