# SPDX-FileCopyrightText: 2026 Andrew Oberstar <andrew@ajoberstar.org>
# SPDX-License-Identifier: AGPL-3.0-only

APPNAME = quixote

PREFIX ?= /usr
BINDIR = $(PREFIX)/bin
SHAREDIR = $(PREFIX)/share/$(APPNAME)

LISP ?= sbcl
LISP_SRC = $(wildcard src/*.lisp)
LISP_TEST = $(wildcard test/*.lisp)

BUILD_DIR = build
QLOT_DIR = .qlot

ifeq ($(OS),Windows_NT)
EXE = .exe
else
EXE =
endif

QUIXOTE = $(BUILD_DIR)/bin/$(APPNAME)$(EXE)

all: $(QUIXOTE)

bootstrap:
	@ if command -v qlot >/dev/null 2>&1; then \
		echo "qlot already installed: $(which qlot)"; \
	else \
		echo "Installing qlot via automatic installed..."; \
		curl -L https://qlot.tech/installer | sh; \
	fi

deps: $(QLOT_DIR)/setup.lisp ;

$(QLOT_DIR)/setup.lisp: qlfile $(wildcard qlfile.lock)
	qlot install >$(CURDIR)/debian/qlot-install.log	2>&1 || \
	(cat $(CURDIR)/debian/qlot-install.log; exit 1)

test: $(QLOT_DIR)/setup.lisp $(LISP_SRC) $(LISP_TEST)
	qlot exec $(LISP) --non-interactive \
	--eval '(ql:quickload "org.ajoberstar.quixote/test")' \
	--eval '(asdf:test-system "org.ajoberstar.quixote")' \
	--eval '(quit)'

$(QUIXOTE): $(QLOT_DIR)/setup.lisp $(LISP_SRC)
	mkdir -p $(dir $@)
	qlot exec $(LISP) --non-interactive \
	--eval '(ql:quickload "org.ajoberstar.quixote")' \
	--eval '(asdf:make "org.ajoberstar.quixote")' \
	--eval '(quit)'

install: $(QUIXOTE)
	install -Dm755 $(QUIXOTE) $(DESTDIR)$(BINDIR)/$(APPNAME)
	install -Dm644 $(APPNAME).service $(DESTDIR)$(PREFIX)/lib/systemd/system/$(APPNAME).service
	find static/ -type f -exec install -Dm644 "{}" "$(DESTDIR)$(SHAREDIR)/{}" \;
	install -Dm755 -d $(DESTDIR)/var/lib/$(APPNAME)

clean:
	rm -rf $(BUILD_DIR)

distclean: clean
	rm -rf $(QLOT_DIR)

.PHONY: all bootstrap deps test clean distclean install
