#================================================================================
PACK_EXT    ?= rpm
# FIXME best build pack on its own OS (deb -> Debian 11,  rpm -> CentOS 7.9)
EXEC_NAME   ?= vlkb
INSTALL_DIR  = /usr/local
VERSION     ?= $(shell git describe)
#================================================================================
BIN_DIR  = bin
DEB_ROOT = debbuild
RPM_ROOT = rpmbuild
#================================================================================

.PHONY: all clean

all: vlkb vlkb-obscore

.PHONY: vlkb vlkb-obscore
vlkb vlkb-obscore:
	make -C common
	make -C $@
	make  EXEC_NAME=$@ $(PACK_EXT)

clean:
	make -C vlkb clean
	make -C vlkb-obscore clean
	make -C common clean



.PHONY: rpm
rpm:
	mkdir -p $(RPM_ROOT)/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
	cp $(EXEC_NAME)/$(EXEC_NAME).spec $(RPM_ROOT)/SPECS
	cp $(EXEC_NAME)/bin/$(EXEC_NAME) $(RPM_ROOT)/SOURCES
	rpmbuild -bb --clean --define "_topdir $(shell pwd)/$(RPM_ROOT)"  --define "_prefix /usr/local" --define "version $(shell git describe | sed -r 's/-/./g')"  $(EXEC_NAME)/$(EXEC_NAME).spec
	find $(RPM_ROOT)/RPMS/* -name '*.rpm' -print0 | xargs -0 cp -t .
	rm -fr $(RPM_ROOT)


.PHONY: deb
deb: PREFIX=$(DEB_ROOT)/$(EXEC_NAME)/usr/local
deb:
	mkdir -p $(DEB_ROOT)/$(EXEC_NAME)/DEBIAN $(PREFIX)
	mkdir -p $(PREFIX)/bin $(PREFIX)/etc/$(EXEC_NAME)
	mkdir -p $(PREFIX)/share/doc/$(EXEC_NAME)
	mkdir -p $(PREFIX)/share/man/man1
	sed 's/Version:.*/Version: $(VERSION)/' $(EXEC_NAME)/$(EXEC_NAME).control > $(DEB_ROOT)/$(EXEC_NAME)/DEBIAN/control
	echo "/usr/local/etc/$(EXEC_NAME)/datasets.conf" > $(DEB_ROOT)/$(EXEC_NAME)/DEBIAN/conffiles
	cp $(EXEC_NAME)/bin/$(EXEC_NAME) $(PREFIX)/bin
	cp $(EXEC_NAME)/$(EXEC_NAME).datasets.conf $(PREFIX)/etc/$(EXEC_NAME)/datasets.conf
	cp $(EXEC_NAME)/$(EXEC_NAME).changelog.Debian $(PREFIX)/share/doc/$(EXEC_NAME)/changelog.Debian
	cp $(EXEC_NAME)/$(EXEC_NAME).copyright $(PREFIX)/share/doc/$(EXEC_NAME)/copyright
	cp $(EXEC_NAME)/$(EXEC_NAME).1 $(PREFIX)/share/man/man1/
	gzip --best -n $(PREFIX)/share/man/man1/$(EXEC_NAME).1
	gzip --best -n $(PREFIX)/share/doc/$(EXEC_NAME)/changelog.Debian
	cd $(DEB_ROOT) && dpkg-deb --root-owner-group --build $(EXEC_NAME) && mv $(EXEC_NAME).deb ../$(EXEC_NAME)-$(VERSION).deb && cd -
	rm -fr $(DEB_ROOT)


