#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

LMSHAREDIR=/usr/share/lemonldap-ng
LMVARDIR  =/var/lib/lemonldap-ng
LMCACHEDIR  =/var/cache/lemonldap-ng
TMP       = $(CURDIR)/debian/tmp

CONFDIR=/etc/lemonldap-ng
export LLNG_SKIP_GPG_TEST=1
export SKIP_NETWORK_TESTS=1

%:
	dh $@

override_dh_auto_configure:
	$(MAKE) lemonldap-ng-common/lib/Lemonldap/NG/Common/Conf/Constants.pm
	$(MAKE) configure STORAGECONFFILE=/etc/lemonldap-ng/lemonldap-ng.ini \
		PERLOPTIONS="INSTALLDIRS=vendor"

override_dh_auto_build: llng_build doc/pages/documentation/current/start.html

llng_build:
	# Generate files excluded from import
	LANG=C $(MAKE) configure common handler manager portal
	# Extract JOSN from doc index
	cat doc/pages/documentation/current/searchindex.js | perl -pe 's/^.*?(\{.*\}).*?$$/$$1/' >debian/index.json
	# Sort JSON, including arrays
	jq --compact-output 'walk(if type == "array" then sort else if type == "object" then to_entries | sort_by(.key) | from_entries else . end end)' > debian/searchindex.js <debian/index.json
	# Insert new JSON in doc index
	perl -000 -i -pe 'BEGIN{open F,"debian/searchindex.js";$$j=<F>;chomp $$j;close F}s/\{.*\}/$$j/' doc/pages/documentation/current/searchindex.js
	pod2man -s 8 -name llng-fastcgi-server fastcgi-server/sbin/llng-fastcgi-server >llng-fastcgi-server.8p

doc/pages/documentation/current/start.html:
	LANG=C $(MAKE) documentation

override_dh_auto_test: doc/pages/documentation/current/start.html
	dh_auto_test

override_dh_auto_install:
	$(MAKE) install \
			DESTDIR=$(CURDIR)/debian/tmp \
			PREFIX=/usr \
			LMPREFIX=/usr/share/lemonldap-ng \
			BINDIR=$(LMSHAREDIR)/bin \
			SBINDIR=/usr/sbin \
			FASTCGISOCKDIR=/var/run/llng-fastcgi-server \
			DOCUMENTROOT=$(LMVARDIR) \
			EXAMPLESDIR=/examples \
			HANDLERDIR=$(LMVARDIR)/handler \
			MANAGERDIR=$(LMSHAREDIR)/manager \
			MANDIR=/usr/share/man \
			PORTALDIR=$(LMSHAREDIR)/portal \
			STORAGECONFFILE=/etc/lemonldap-ng/lemonldap-ng.ini \
			TOOLSDIR=$(LMSHAREDIR)/ressources \
			CONFDIR=$(CONFDIR) \
			CRONDIR=/etc/cron.d \
			DATADIR=$(LMVARDIR) \
			CACHEDIR=$(LMCACHEDIR) \
			APACHEVERSION=2.X \
			APACHEUSER=www-data \
			APACHEGROUP=www-data \
			DEFDOCDIR=/usr/share/doc/lemonldap-ng \
			UWSGIYAMLDIR=/etc/uwsgi/apps-available \
			USEDEBIANLIBS=yes
	find $(TMP)/$(LMSHAREDIR) -type f -name '.*.swp' -delete
	# Generate minified files removed by uscan
	for i in $$(find $(TMP)/$(LMSHAREDIR) -type f -name '*.js'); do \
		echo -n "compressing $$i: "; \
		uglifyjs --comments '/Copyr/i' $$i >$${i%%.js}.min.js; \
		echo done; \
	done
	for i in $$(find $(TMP)/$(LMSHAREDIR) -type f -name '*.css'); do \
		echo -n "compressing $$i: "; \
		yui-compressor $$i >$${i%%.css}.min.css; \
		echo done; \
	done
	rm -rf $(TMP)/usr/share/lemonldap-ng/usr/lib/systemd

override_dh_compress:
	dh_compress -X favicon.ico

override_dh_missing:
	dh_missing -Xexamples/ -Xetc/cron.d -Xllng-fastcgi-server
