#     Copyright (C) 2019 Didier Kryn <kryn@in2p3.fr> -- See LICENSE
# 'make'           build the executable
# 'make clean'     remove object files, keep libraries and executable
# 'make install'   install executable, etc. -- listed in  $(INSTALLED_FILES)
# 'make cleanall'  remove everything but source files and installed files
# 'make uninstall' remove installed files
# You must be root to make install/uninstall
#
#
#  In this makefile we rely on makefiles in other directories and we need
# to know their dependencies. These other makefiles provide targets to
# print their dependencies


GUI_DIR   := GTK
WATCH_DIR := watch
ANNEX_DIR := annex
ICON_DIR  := icon

VPATH := $(GUI_DIR):$(WATCH_DIR):$(ANNEX_DIR)

# Get list of dependencies from sub-makefiles
GUI_DEPS   := $(shell $(MAKE) -s -r -C $(GUI_DIR)   print_deps)
WATCH_DEPS := $(shell $(MAKE) -s -r -C $(WATCH_DIR) print_deps)
ANNEX_DEPS := $(shell $(MAKE) -s -r -C $(ANNEX_DIR) print_deps)

INSTALLED_FILES = /usr/bin/hopman-$(GUI_DIR) /usr/bin/hopman \
/usr/share/man/man8/hopman.8.gz /usr/share/man/man8/hopmanrc.8.gz \
/etc/default/hopmanrc /usr/share/pixmaps/hopman.png \
/usr/share/applications/hopman.desktop /usr/share/doc/hopman/copyright

.SUFFIXES:

all: $(GUI_DIR)/hopman

#--------- Executable
$(GUI_DIR)/hopman: $(GUI_DEPS)
	@$(MAKE) -r -C $(GUI_DIR) hopman

$(WATCH_DIR)/watch.a: $(WATCH_DEPS)
	@$(MAKE) -r -C $(WATCH_DIR) watch.a

$(ANNEX_DIR)/annex.a: $(ANNEX_DEPS)
	@$(MAKE) -r -C $(ANNEX_DIR) annex.a

#--------- Installation
# Essentials:
install: $(INSTALLED_FILES)

/usr/bin/hopman: /usr/bin/hopman-$(GUI_DIR)
	(cd /usr/bin; ln -sf hopman-$(GUI_DIR) hopman)

/usr/bin/hopman-$(GUI_DIR): $(GUI_DIR)/hopman
	cp $< $@

/usr/share/man/man8/hopman.8.gz: doc/man/man8/hopman
	gzip -c  $<   > $@

/usr/share/man/man8/hopmanrc.8.gz: doc/man/man8/hopmanrc
	gzip -c  $<   > $@

/etc/default/hopmanrc: $(ANNEX_DIR)/hopmanrc
	cp  $<  $@

/usr/share/pixmaps/hopman.png: $(ICON_DIR)/removable-media-32x32.png
	cp $<  $@

/usr/share/applications/hopman.desktop: hopman.desktop
	cp $<  $@

/usr/share/doc/hopman/copyright: LICENSE /usr/share/doc/hopman
	cp $<  $@

/usr/share/doc/hopman:
	mkdir $@

#------- Cleaning
clean:
	$(MAKE) -r -C $(WATCH_DIR) clean
	$(MAKE) -r -C $(ANNEX_DIR) clean
	$(MAKE) -r -C $(GUI_DIR) clean
	rm -vf $(wildcard doc/man/man8/*~)
	rm -vf $(wildcard *~)

cleanall:
	$(MAKE) -r -C $(WATCH_DIR) cleanall
	$(MAKE) -r -C $(ANNEX_DIR) cleanall
	$(MAKE) -r -C $(GUI_DIR)   cleanall
	rm -vf $(wildcard doc/man/man8/*~)
	rm -vf $(wildcard *~)

uninstall:
	rm -vf $(INSTALLED_FILES)
	rm -rvf /usr/share/doc/hopman

.PHONY: clean cleanall uninstall print_all_deps
.SILENT: clean cleanall uninstall print_all_deps

#-------- Utilities
print_all_deps:
	echo Dependencies of $(GUI_DIR)/hopman: $(GUI_DEPS)
	echo Dependencies of $(WATCH_DIR)/watch.a: $(WATCH_DEPS)
	echo Dependencies of $(ANNEX_DIR)/annex.a: $(ANNEX_DEPS)
