#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk

IEC61850_VERSION       = 1.6.1
IEC61850_OPTS          = $(shell perl -MConfig -e 'print join(" ", @Config{qw(ccflags optimize cccdlflags)}, "-I$$Config{archlib}/CORE")')
IEC61850_FOLDER        = libiec61850-$(IEC61850_VERSION)
PERL_INSTALLARCHLIB    = $(shell perl -MConfig -e 'print $$Config{installarchlib}')
PERL_INSTALLVENDORARCH = $(shell perl -MConfig -e 'print $$Config{installvendorarch}')
# Hardening options
IEC61850_HARDENING     = -fstack-protector-strong -D_FORTIFY_SOURCE=2
IEC61850_LDOPTS        = -Wl,-z,relro,-z,now -D_FORTIFY_SOURCE=2

# Skip all tests but the only really important for Debian & linux
TEST_FILES = t/01compile.t t/agent/tools/linux.t \
	$(shell echo t/tasks/inventory/linux/*.t t/tasks/inventory/linux/*/*.t)

# By default, set COMMENTS with converted source timestamp in UTC
DEB_AGENT_COMMENTS ?= Built by Debian,Source time: $(shell date -u +'%F %R' -d @$(SOURCE_DATE_EPOCH))

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -- PREFIX=/usr SYSCONFDIR=/etc/glpi-agent LOCALSTATEDIR=/var/lib/glpi-agent VERSION=$(DEB_VERSION_UPSTREAM_REVISION) COMMENTS="$(DEB_AGENT_COMMENTS)"

override_dh_auto_test:
	dh_auto_test -- TEST_FILES="$(TEST_FILES)"

override_dh_auto_build:
	dh_auto_build

	# Fix glpi-agent.service other service dependency
	sed -ri -e 's/syslog.target\s*//' contrib/unix/glpi-agent.service

	# Build libiec61850 support
	curl -L -o $(IEC61850_VERSION).tar.gz https://github.com/g-bougard/libiec61850/archive/refs/tags/$(IEC61850_VERSION).tar.gz
	tar xzf $(IEC61850_VERSION).tar.gz
	make -C $(IEC61850_FOLDER) -j4 CFLAGS="-fPIC $(IEC61850_HARDENING)" CPP_FLAGS="$(IEC61850_LDOPTS)"
	swig -Wall -O -I$(IEC61850_FOLDER)/src/common/inc -I$(IEC61850_FOLDER)/src/iec61850/inc -I$(IEC61850_FOLDER)/src/mms/inc -I$(IEC61850_FOLDER)/src/goose -perl5 $(IEC61850_FOLDER)/iec61850-perl/iec61850.i
	gcc $(IEC61850_HARDENING) -c $(IEC61850_FOLDER)/iec61850-perl/iec61850_wrap.c -I$(PERL_INSTALLARCHLIB)/CORE -I$(IEC61850_FOLDER)/src/common/inc -I$(IEC61850_FOLDER)/src/iec61850/inc -I$(IEC61850_FOLDER)/src/mms/inc -I$(IEC61850_FOLDER)/hal/inc -I$(IEC61850_FOLDER)/src/logging -I$(IEC61850_FOLDER)/src/r_session $(IEC61850_OPTS) -fmax-errors=5 -Wno-deprecated-declarations -o $(IEC61850_FOLDER)/iec61850-perl/iec61850_wrap.o
	gcc -shared $(IEC61850_LDOPTS) $(IEC61850_FOLDER)/iec61850-perl/iec61850_wrap.o $(IEC61850_FOLDER)/build/libiec61850.a -o $(IEC61850_FOLDER)/iec61850-perl/iec61850.so

	perl debian/refresh-install-files

override_dh_auto_install:
	dh_auto_install --destdir debian/tmp

	# Install libiec61850 support
	install -D $(IEC61850_FOLDER)/iec61850-perl/iec61850.so debian/tmp$(PERL_INSTALLVENDORARCH)/auto/iec61850/iec61850.so
	install -D $(IEC61850_FOLDER)/iec61850-perl/iec61850.pm debian/tmp$(PERL_INSTALLVENDORARCH)/iec61850.pm

# Use gzip compression to keep best compatibility with older debian/ubuntu distros
override_dh_builddeb:
	dh_builddeb -- -Zgzip
