#!/usr/bin/make -f

export DH_VERBOSE := 1
export GOTOOLCHAIN := local
export CGO_ENABLED := 1

GOFLAGS := -mod=vendor -buildvcs=false
export GOFLAGS
GOCACHE := $(CURDIR)/.gocache
export GOCACHE

VERSION  := $(shell dpkg-parsechangelog -SVersion)
UPSTREAM := $(shell dpkg-parsechangelog -SVersion | sed 's/-[^-]*$$//')
OUT      := build/out

%:
	dh $@

override_dh_auto_clean:
	dh_auto_clean
	rm -rf build .gocache
	rm -f cmd/caddy/plugin.go

override_dh_auto_configure:
	cp debian/plugin.go cmd/caddy/plugin.go
	mkdir -p $(OUT)

override_dh_auto_build:
	go build \
	  -buildmode=pie \
	  -ldflags "-X github.com/caddyserver/caddy/v2.CustomVersion=v$(UPSTREAM) \
	            -compressdwarf=false -linkmode=external" \
	  -o $(CURDIR)/$(OUT)/caddy ./cmd/caddy
	$(OUT)/caddy completion bash > build/caddy.bash
	$(OUT)/caddy completion zsh > build/_caddy
	$(OUT)/caddy completion fish > build/caddy.fish
	$(OUT)/caddy manpage --directory build/manpages

override_dh_auto_test:
ifneq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	@echo "Skipping tests (DEB_BUILD_OPTIONS=nocheck)"
else
	go test -short -skip '^TestFileRotationPreserveMode$$' ./...
	$(OUT)/caddy version | grep -qx "v$(UPSTREAM)"
	$(OUT)/caddy list-modules | grep -qx layer4
	$(OUT)/caddy list-modules | grep -qx dns.providers.cloudflare
endif

override_dh_auto_install:
	install -Dm755 $(OUT)/caddy debian/caddy/usr/bin/caddy

	install -Dm644 caddy.service debian/caddy/lib/systemd/system/caddy.service
	install -Dm644 caddy-api.service debian/caddy/lib/systemd/system/caddy-api.service
	install -Dm644 caddy.tmpfiles debian/caddy/usr/lib/tmpfiles.d/caddy.conf
	install -Dm644 caddy.sysusers debian/caddy/usr/lib/sysusers.d/caddy.conf

	install -Dm644 Caddyfile debian/caddy/etc/caddy/Caddyfile
	install -d debian/caddy/etc/caddy/conf.d

	install -Dm644 index.html debian/caddy/usr/share/caddy/index.html

	install -Dm644 build/caddy.bash debian/caddy/usr/share/bash-completion/completions/caddy
	install -Dm644 build/_caddy debian/caddy/usr/share/zsh/vendor-completions/_caddy
	install -Dm644 build/caddy.fish debian/caddy/usr/share/fish/vendor_completions.d/caddy.fish

	install -d debian/caddy/usr/share/man/man8
	install -m644 build/manpages/* debian/caddy/usr/share/man/man8/

override_dh_dwz:
	@echo "Skipping dh_dwz: dwz cannot handle Go DWARF (.debug_addr)"
