.POSIX:

.PHONY: all
all: publications.txt

.PHONY: test

# Remove `.gitignore`d files interactively.
.PHONY: clean
clean:
	git clean -Xi

URL = http://boundvariable.org
task.txt:
	curl -sSL $(URL)/task.shtml \
	| pandoc --from html --to plain --columns=79 \
	| awk ' \
	  /^An Urgent Appeal$$/           { body = 1;      } \
	  /^Carnegie Mellon University$$/ { print; exit;   } \
	  /^[[:punct:]]+$$/               { getline; next; } \
	  body; \
	' > $@
sha1sums.txt:
	curl -sSL $(URL)/task.shtml \
	| pandoc --from html --to plain --columns=79 \
	| awk ' \
	  $$1 == "[]"    { file = $$2; } \
	  $$1 == "SHA-1" { print $$3, "*" file; } \
	' > $@
codex-key.txt: task.txt
	awk 'key { print; exit; } /decryption key/ { key = 1; }' task.txt > $@
codex.umz sandmark.umz: sha1sums.txt
	curl -sSL $(URL)/$@ > $@
	awk '$$2 == "*$@"' sha1sums.txt | sha1sum -c
sandmark-output.txt um.um:
	curl -sSL $(URL)/$@ > $@
um-spec.txt:
	curl -sSL $(URL)/$@ | awk 'sub(/ *$$/, "") || 1;' > $@

um: um.cpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) um.cpp $(LDLIBS) -o $@

test: um sandmark.umz sandmark-output.txt
	{ time ./um sandmark.umz; } \
	| tee /dev/tty \
	| diff -q sandmark-output.txt -

umix.um: um codex.umz codex-key.txt
	# It's faster if we don't output to `/dev/tty`, but it looks cool.
	{ cat codex-key.txt; echo 'p'; } \
	| { time ./um codex.umz; } \
	| { tee /dev/stderr | cat -v > /dev/tty; } 2>&1 \
	| LC_ALL=C awk ' \
	  program; \
	  !program && program = match($$0, /UM program follows colon:/) { \
	    print substr($$0, RSTART+RLENGTH); \
	  } \
	' > $@
	echo

.PHONY: publications.txt
.PRECIOUS: publications.txt
publications.txt: um umix.um
	publications=$$(cat $@); \
	{ \
	  ! [ "$$publications" ] || echo "$$publications"; \
	  { time ./um umix.um; } \
	  | tee /dev/tty \
	  | awk ' \
	    match($$0, /[A-Z]{5}\.[A-Z]{3}=[0-9]+@[0-9]+\|[0-9a-f]{31}/) { \
	      print substr($$0, RSTART, RSTART+RLENGTH); \
	    } \
	  '; \
	} \
	| awk '!seen[$$0]++' > $@