. "$BST_LIB"
# busybox 1.36.1 ships no `make` applet, so a bare `make` is unambiguously this
# port -- no update-alternatives name needed (cf. patch.patch / tar.tar).
require make make/present

tmp=${TMPDIR:-/tmp}/bst-make.$$
mkdir -p "$tmp" 2>/dev/null
mf="$tmp/Makefile"

# Recipe lines must start with a literal tab; printf keeps that explicit rather
# than trusting a here-doc to survive editing.
{
  printf 'GREETING = HELLO-FROM-MAKE\n'
  printf 'all: dep\n'
  printf '\t@echo $(GREETING)\n'
  printf 'dep:\n'
  printf '\t@echo DEP-FIRST\n'
  printf 'out.txt:\n'
  printf '\t@echo FILE-BODY > $@\n'
  printf 'boom:\n'
  printf '\t@exit 3\n'
} > "$mf" 2>/dev/null

# provenance: GNU make prints "GNU Make <ver>".
check_out make/version "GNU Make" make --version

# Default goal + prerequisite. Every recipe line is a fork+exec of /bin/sh, so
# this is the case that exercises make's core mechanism on this runtime.
out=$(make -C "$tmp" 2>&1); rc=$?
check_eq make/default-rc 0 "$rc"
case "$out" in
  *HELLO-FROM-MAKE*) bst_ok make/echo-rule ;;
  *) bst_notok make/echo-rule "rc=$rc $(_bst_1line "$out")" ;;
esac
# dep's recipe must run before all's -- ordering, not just presence.
case "$out" in
  *DEP-FIRST*HELLO-FROM-MAKE*) bst_ok make/prereq-order ;;
  *) bst_notok make/prereq-order "rc=$rc $(_bst_1line "$out")" ;;
esac

# A recipe that redirects into $@: the shell creates the target via open(O_CREAT)
# (not creat(2), which is ENOSYS here -- brintos/linux#13).
check     make/file-target make -C "$tmp" out.txt
check_out make/file-body   "FILE-BODY" cat "$tmp/out.txt"

# A failing recipe stops the build: make reports the error and exits 2.
check_rc make/fail-rc 2 make -C "$tmp" boom

rm -rf "$tmp"
