# JoeyLib top-level Makefile.
#
# Usage:
#   source toolchains/env.sh    (first, every shell session)
#   make                        builds every target whose toolchain is present
#   make iigs                   builds Apple IIgs only
#   make amiga                  builds Commodore Amiga only
#   make atarist                builds Atari ST only
#   make dos                    builds MS-DOS only
#   make clean                  removes all build outputs
#
# The build references cross tools exclusively from toolchains/, set up
# by sourcing toolchains/env.sh. Do not invoke make without sourcing
# env.sh first or builds will fail with missing tool errors.

REPO_DIR := $(abspath $(dir $(firstword $(MAKEFILE_LIST))))

# Detect which toolchains are actually available.
HAVE_IIGS    := $(shell [ -x "$(IIGS_CC)"   ] && echo 1)
HAVE_AMIGA   := $(shell [ -x "$(AMIGA_CC)"  ] && echo 1)
HAVE_ATARIST := $(shell [ -x "$(ST_CC)"     ] && echo 1)
HAVE_DOS     := $(shell [ -x "$(DOS_CC)"    ] && echo 1)

ALL_TARGETS :=
ifeq ($(HAVE_IIGS),1)
    ALL_TARGETS += iigs
endif
ifeq ($(HAVE_AMIGA),1)
    ALL_TARGETS += amiga
endif
ifeq ($(HAVE_ATARIST),1)
    ALL_TARGETS += atarist
endif
ifeq ($(HAVE_DOS),1)
    ALL_TARGETS += dos
endif

.PHONY: all iigs iigs-disk iigs-verify amiga atarist dos blank-check tools clean help status

all: $(ALL_TARGETS) tools
ifeq ($(ALL_TARGETS),)
	@echo "No toolchains detected. Run ./toolchains/install.sh and source toolchains/env.sh."
	@exit 1
endif

tools:
	@$(MAKE) -f $(REPO_DIR)/make/tools.mk

iigs:
	@$(MAKE) -f $(REPO_DIR)/make/iigs.mk

iigs-disk:
	@$(MAKE) -f $(REPO_DIR)/make/iigs.mk iigs-disk

iigs-verify:
	@$(MAKE) -f $(REPO_DIR)/make/iigs.mk iigs-verify

amiga:
	@$(MAKE) -f $(REPO_DIR)/make/amiga.mk

atarist:
	@$(MAKE) -f $(REPO_DIR)/make/atarist.mk

dos:
	@$(MAKE) -f $(REPO_DIR)/make/dos.mk

# Compile + link-check the new-port template (src/blank/blank.c) with the host
# cc. No toolchain needed; keeps the template from bit-rotting as the lib grows.
blank-check:
	@$(REPO_DIR)/scripts/check-blank.sh

clean:
	rm -rf $(REPO_DIR)/build

status:
	@echo "Toolchain availability:"
	@echo "  iigs:    $(if $(HAVE_IIGS),yes,NO)"
	@echo "  amiga:   $(if $(HAVE_AMIGA),yes,NO)"
	@echo "  atarist: $(if $(HAVE_ATARIST),yes,NO)"
	@echo "  dos:     $(if $(HAVE_DOS),yes,NO)"

help:
	@echo "Targets: iigs amiga atarist dos all clean status help"
	@echo "         iigs-disk iigs-verify (IIgs MAME visual check)"
	@echo "         blank-check (host-cc smoke test of the new-port template)"
	@echo "Source toolchains/env.sh first (blank-check needs no toolchain)."
