VERSION := $(shell cat VERSION)
DIST    := dist
NAME    := nhanhvps

SHELL_SCRIPTS := $(shell find bin lib modules install tests -type f \
                   \( -name '*.sh' -o -name 'action' -o -name 'menu' \) 2>/dev/null) \
                 setup.sh \
                 packaging/make-release.sh

.PHONY: all check syntax lint test install setup package release repo clean

all: check test

## bash -n on every script
syntax:
	@fail=0; \
	for f in $(SHELL_SCRIPTS); do \
	  head -1 "$$f" | grep -q '^#!.*bash' || continue; \
	  bash -n "$$f" || { echo "SYNTAX: $$f"; fail=1; }; \
	done; \
	if [ $$fail -eq 0 ]; then echo "syntax: OK ($(words $(SHELL_SCRIPTS)) files)"; else exit 1; fi

## shellcheck, warnings are errors
lint:
	@if command -v shellcheck >/dev/null 2>&1; then \
	  shellcheck -x -S warning $(SHELL_SCRIPTS) && echo "shellcheck: OK"; \
	else echo "shellcheck: SKIPPED (not installed)"; fi

check: syntax lint

test:
	@bash tests/run.sh

## read-only end-to-end checks, safe on any machine
smoke:
	@bash tests/smoke/run-smoke.sh

## install into a running system (root)
## one-command install of this tree on this host
setup:
	@sudo bash setup.sh $(SETUP_ARGS)

install:
	@sudo bash install/install.sh

## build a .deb for local testing
package:
	@bash packaging/build-deb.sh $(VERSION)

## build the files to publish; BASE_URL is required, there is no default
release:
	@test -n "$(BASE_URL)" || { \
	  echo "usage: make release BASE_URL=https://your-host/dl"; \
	  echo "       (there is no default: a guessed address is a domain nobody owns)"; \
	  exit 2; }
	@bash packaging/make-release.sh --base-url "$(BASE_URL)"

## build an apt repository; pass KEY=<gpg-key-id> to sign it
repo:
	@bash packaging/build-repo.sh $(VERSION) $(if $(KEY),--key $(KEY),)

clean:
	@rm -rf $(DIST)
