# ----------------------------------------------------------------------
# Top-level project Makefile
#
# Builds all library subdirectories first, followed by programs and tests.
# Each listed subdirectory must contain its own Makefile.
# ----------------------------------------------------------------------

# Libraries must be built before programs that link against them.
LIB_DIRS := \
	tsc_list \
	tsc_tree \
	tsc_hash \
	tsc_deque \
	tsc_vector \
	mvs_types \
	mvs_utils \
	mvs_datetime \
	aws_tape \
	ebcdic_utils \
	vdasd \
	vpds \
	vtape \
	viebcopy

# Programs and other non-library targets.
APP_DIRS := \
	awsdump \
	cpttape \
	cpftape \
	tests

ALL_DIRS := $(LIB_DIRS) $(APP_DIRS)

# Installation is intentionally limited to the two end-user tape utilities.
# The TSCLIB static libraries and headers remain source-tree/build dependencies
# and are not installed system-wide by this Makefile.
PREFIX  ?= /usr/local
BINDIR  ?= $(PREFIX)/bin
DESTDIR ?=

.PHONY: all libs apps check test install uninstall clean distclean $(ALL_DIRS)

# Default target
all: libs apps

# Build all libraries in the listed order.
libs:
	@set -e; \
	for dir in $(LIB_DIRS); do \
		echo "==> Building $$dir"; \
		$(MAKE) -C $$dir; \
	done

# Build all applications/tests after the libraries complete.
apps: libs
	@set -e; \
	for dir in $(APP_DIRS); do \
		echo "==> Building $$dir"; \
		$(MAKE) -C $$dir; \
	done

# Build all test executables and run the complete test set.
check: libs
	$(MAKE) -C tests check

# Conventional alias.
test: check

# Build one named subdirectory directly, for example:
#     make vtape
$(ALL_DIRS):
	$(MAKE) -C $@


# Install only the supported end-user command-line utilities.
# DESTDIR is honored for staged/package installation.
install: cpttape cpftape
	install -d "$(DESTDIR)$(BINDIR)"
	install -m 0755 cpttape/cpttape "$(DESTDIR)$(BINDIR)/cpttape"
	install -m 0755 cpftape/cpftape "$(DESTDIR)$(BINDIR)/cpftape"

# Remove only files installed by the target above.
uninstall:
	rm -f "$(DESTDIR)$(BINDIR)/cpttape"
	rm -f "$(DESTDIR)$(BINDIR)/cpftape"

# Propagate clean to every subdirectory.
clean:
	@set -e; \
	for dir in $(ALL_DIRS); do \
		echo "==> Cleaning $$dir"; \
		$(MAKE) -C $$dir clean; \
	done

# Propagate distclean when supported.
distclean:
	@set -e; \
	for dir in $(ALL_DIRS); do \
		echo "==> Distcleaning $$dir"; \
		$(MAKE) -C $$dir distclean; \
	done
