#!/usr/bin/make -f

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

# Get version from changelog as well as lsb_release
# to compute unique build version (useful for repo mirroring systems doing file pooling)
PKG_VERSION  := $(shell dpkg-parsechangelog | grep -E '^Version:' | cut -d' ' -f2)
DIST_NAME    := $(shell lsb_release -si)
DIST_RELEASE := $(shell lsb_release -sc)
DIST_VERSION := $(shell lsb_release -sr)
PKG_VERSION_TAG := $(PKG_VERSION)+$(DIST_NAME).$(DIST_VERSION).$(DIST_RELEASE)
SUBSTVARS_BINARY_VERSION := -Vbinary:Version="$(PKG_VERSION_TAG)"
SUBSTVARS_SOURCE_VERSION := -Vsource:Version="$(PKG_VERSION_TAG)"

# Detect Python interpreter
ifneq (, $(shell which python3))
	INTERPRETER_NAME := python3
	INTERPRETER_PATH := $(shell which python3)
else ifneq (, $(shell which python))
	INTERPRETER_NAME := python
	INTERPRETER_PATH := $(shell which python)
else ifneq (, $(shell which python))
	INTERPRETER_NAME := python2
	INTERPRETER_PATH := $(shell which python2)
endif
SUBSTVARS_PYTHON_CUSTOM := -VpythonCustom:Depends="$(INTERPRETER_NAME)"

build: build-arch build-indep
build-arch:
build-indep:

clean:
	dh_testdir
	dh_testroot
	dh_clean 

install:
ifeq (, $(INTERPRETER_PATH))
	$(error Python interpreter could not be detected)
endif
	dh_testdir
	dh_testroot
	dh_clean -k 
	dh_installdirs

binary-arch: build install
binary-indep: build install
	dh_testdir -i
	dh_testroot -i
	dh_installchangelogs -i
	dh_installdocs -i
	dh_install -i
	sed -i 's|^#!.*python.*|#!$(INTERPRETER_PATH)|' debian/*/usr/sbin/*
	dh_installinit -i --name megaclisas-statusd
	dh_link -i
	dh_strip -i
	dh_compress -i
	dh_fixperms -i
	dh_installdeb -i
	dh_shlibdeps -i
	dh_gencontrol -i -- -v"$(PKG_VERSION_TAG)" $(SUBSTVARS_BINARY_VERSION) $(SUBSTVARS_SOURCE_VERSION) $(SUBSTVARS_PYTHON_CUSTOM)
	dh_md5sums -i
	dh_builddeb -i

binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install
