#!/usr/bin/make -f

export DH_GOLANG_EXCLUDES := scripts/fork_go_templates tpl/tplimpl/embedded/generate

# Prevent TestImageResize8BitPNG from failing due to pkgbinarymangler
# recompressing our test PNG image on Ubuntu
export NO_PNG_PKG_MANGLE := 1

# Prepare -ldflags arguments for Hugo version information

include /etc/os-release

PACKAGE := $(shell sed -n "s/^XS-Go-Import-Path: \(.*\)/\1/p" debian/control)

DATE_FMT = %Y-%m-%dT%H:%M:%SZ
ifdef SOURCE_DATE_EPOCH
	BUILD_DATE ?= $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+$(DATE_FMT)" 2>/dev/null || date -u -r "$(SOURCE_DATE_EPOCH)" "+$(DATE_FMT)" 2>/dev/null || date -u "+$(DATE_FMT)")
else
	BUILD_DATE ?= $(shell date -u "+$(DATE_FMT)")
endif

VENDOR_INFO := $(ID):$(shell dpkg-parsechangelog --show-field Version)

LDFLAGS := -ldflags \
	'-X "$(PACKAGE)/common/hugo.buildDate=$(BUILD_DATE)" \
	 -X "$(PACKAGE)/common/hugo.vendorInfo=$(VENDOR_INFO)"'

TAGS := -tags 'dev extended'

HUGO := _build/bin/hugo

%:
	dh $@ --builddirectory=_build --buildsystem=golang

execute_after_dh_auto_configure:
	# github.com/gohugoio/testmodBuilder is for testing only
	# and will not be packaged separately for Debian
	cp -a debian/go/src/github.com/gohugoio/testmodBuilder \
	    _build/src/github.com/gohugoio/
	
	# github.com/gohugoio/go-i18n/v2 (Fix multiple unknown language codes)
	# See https://github.com/gohugoio/hugo/issues/7838
	cp -a debian/go/src/github.com/gohugoio/go-i18n \
	    _build/src/github.com/gohugoio/
	
	# github.com/gohugoio/locales
	cp -a /usr/share/gocode/src/github.com/go-playground/locales \
	    _build/src/github.com/gohugoio/
	cd _build/src/github.com/gohugoio/locales && \
	    sed -i 's/go-playground/gohugoio/' *.go */*.go
	
	# github.com/gohugoio/localescompressed
	cp -a debian/go/src/github.com/gohugoio/localescompressed \
	    _build/src/github.com/gohugoio/
	
	# Convert symlinks to real directories where necessary to allow
	# installation of local libraries (Note: Do not remove this snippet!)
	cd _build/src/github.com && \
	    for i in ; do \
	        if [ -L "$$i" ]; then \
	            $(RM) $$i && \
	            mkdir $$i && \
	            for j in /usr/share/gocode/src/github.com/$$i/*; do \
	                cp -a $$j $$i/; \
	            done; \
	        fi; \
	    done

override_dh_auto_build:
	dh_auto_build -O--buildsystem=golang -- $(LDFLAGS) $(TAGS)
	$(HUGO) version
	mkdir -p debian/completion/bash debian/completion/zsh
	$(HUGO) gen autocomplete --type=bash > debian/completion/bash/hugo
	$(HUGO) gen autocomplete --type=zsh > debian/completion/zsh/_hugo
	$(HUGO) gen man --dir=debian/man
	# TODO: Add "hugo-docs" package in the future?
	#$(HUGO) -s docs -d public/html --uglyURLs

# Disable network access during testing by using -short flag
override_dh_auto_test:
	CI=true dh_auto_test -- -short -timeout 120m

override_dh_auto_install:
	dh_auto_install -- --no-source
