#!/bin/sh
# Alternative to build0 that supports a --until flag to include only a subset
# of layers.
#   $ ./build1 --until 050
UNTIL_LAYER=${2:-zzz}

set -v
set -e  # stop immediately on error

# Some environment variables that can be passed in. For example, to turn off
# optimization:
#   $ CFLAGS=-g ./build1
test "$CXX" || export CXX=c++
test "$CC" || export CC=cc
test "$CFLAGS" || export CFLAGS="-g -O2"
export CFLAGS="$CFLAGS -Wall -Wextra -ftrapv -fno-strict-aliasing"
export CXXFLAGS="-std=c++98 $CFLAGS"  # CI has an ancient version; don't expect recent dialects

# Outline:
# [0-9]*.cc -> mu.cc -> mu_bin
# (layers)   |        |
#          tangle   $CXX

$CXX $CFLAGS ../../tools/enumerate.cc -o ../../tools/enumerate

cd ../../tools
  # auto-generate various lists (ending in '_list' by convention) {
  # list of function declarations, so I can define them in any order
  grep -h "^[^ #].*) {" tangle.cc  |sed 's/ {.*/;/'  > tangle.function_list
  # list of tests to run
  grep -h "^[[:space:]]*void test_" tangle.cc  |sed 's/^\s*void \(.*\)() {$/\1,/'  > tangle.test_list
  grep -h "^\s*void test_" tangle.cc  |sed 's/^\s*void \(.*\)() {.*/"\1",/'  > tangle.test_name_list
  # }
  $CXX $CXXFLAGS tangle.cc -o tangle
  ./tangle test
cd ../archive/1.vm

cd termbox
  $CC $CFLAGS -c termbox.c
  $CC $CFLAGS -c utf8.c
  ar rcs libtermbox.a *.o
cd ..

LAYERS=$(../../tools/enumerate --until $UNTIL_LAYER  |grep '\.cc$')
../../tools/tangle $LAYERS  > mu.cc
# auto-generate function declarations, so I can define them in any order
# functions start out unindented, have all args on the same line, and end in ') {'
#
#                                      \/ ignore struct/class methods
grep -h "^[^[:space:]#].*) {$" mu.cc  |grep -v ":.*("  |sed 's/ {.*/;/'  > function_list
# auto-generate list of tests to run
grep -h "^\s*void test_" mu.cc  |sed 's/^\s*void \(.*\)() {.*/\1,/'  > test_list
grep -h "^\s*void test_" mu.cc  |sed 's/^\s*void \(.*\)() {.*/"\1",/'  > test_name_list
$CXX $CXXFLAGS mu.cc termbox/libtermbox.a -o mu_bin

## [0-9]*.mu -> core.mu

MU_LAYERS=$(../../tools/enumerate --until $UNTIL_LAYER  |grep '\.mu$') || exit 0  # ok if no .mu files
cat $MU_LAYERS  > core.mu
