################################################
# File Testing
#

ABELLA = $(if $(equal $(OSTYPE), Win32),$(CWD)/../abella.exe,$(CWD)/../abella)
export

if $(not $(file-exists $(ABELLA)))
    eprintln(Need to first build $(ABELLA))

FILE_NAMES[] = $(rootname $(find . -name *.thm))

.SCANNER: %.out %.thc: %.thm
    section
        # Compute dependencies
        deps[] =
        awk($<)
        case $'Import "\(.*\)"\.'
            deps[] += $(addsuffix .thc, $1)
            export

        # Easier to depend on all specs rather than trace through accumulates
        deps[] += $(glob i, *.sig *.mod)

        println($"$@: $< $(deps)")

%.out: $(ABELLA)
    $(ABELLA) $*.thm >& $*.out || true

%.thc: $(ABELLA)
    $(ABELLA) $*.thm -c $@ -o $*.out

.SUBDIRS: $(subdirs .)
    foreach(name, $(rootname $(glob i, *.thm)))
        .PHONY: $(name)
        $(name): $(name).out
            cat $(name).out

        .PHONY: $(name)-tail
        $(name)-tail: $(name).out
            tail -100 $(name).out

section
    .PHONY: theorems
    theorems: $(addsuffix .thc, $(FILE_NAMES))

################################################
# HTML Output
#

ANNOTATE_THM = $(CWD)/html-files/annotate_thm.rb
DETAILS_RHTML = $(CWD)/html-files/details.rhtml

.SUBDIRS: $(subdirs P, .)
    foreach(name, $(rootname $(glob i, *.thm)))
        $(name).html $(name)-details.html: $(name).thc $(name).out \
          $(ANNOTATE_THM) $(DETAILS_RHTML)
            echo Processing $(name)

            echo $(name) > name
            head -1 $(name).thm > title-line

            ruby $(ANNOTATE_THM) $(name).thm > $(name).html
            $(ABELLA) -a $(name).thm > details
            erb $(DETAILS_RHTML) > $(name)-details.html

            rm -f name title-line spec-name spec-sig spec-mod \
                  reasoning details

section
    .PHONY: html
    html: $(addsuffix .html, $(FILE_NAMES))

.PHONY: upload-html
upload-html: html
    section
        # Create an examples subdir within examples
        rm -rf examples examples.tar.gz
        cp -r . examples
        # rm $(set-diff $(filter-out %.html %.thm %.mod %.sig, $(ls R, examples)), $(subdirs examples))
        rm -r examples/html-files examples/OMakefile
        bash -c "/usr/bin/find examples -maxdepth 1 -type f -exec rm -f '{}' ';'"
        cp index.html examples/
        bash -c "/usr/bin/find examples -type d -exec chmod 775 '{}' ';'"
        bash -c "/usr/bin/find examples -type f -exec chmod 664 '{}' ';'"
        tar -czf examples.tar.gz --exclude='*.thc' --exclude='*.out' examples
        rm -rf examples
