# Rebuild every figure, then run the private test scripts listed in README.md.
#   Rscript make_all.R            all chapters
#   Rscript make_all.R 4 7        only chapters 4 and 7
# Each chapter script runs in a fresh R process, so one chapter cannot affect another.

here <- local({
  a <- grep("^--file=", commandArgs(FALSE), value = TRUE)
  dirname(normalizePath(sub("^--file=", "", a[1])))
})
args <- commandArgs(TRUE)
chapters <- if (length(args)) as.integer(args) else 1:13
rscript <- file.path(R.home("bin"), "Rscript")
status <- c()
for (ch in chapters) {
  scripts <- sort(Sys.glob(file.path(here, sprintf("ch%02d_*.R", ch))))
  checks <- Sys.glob(file.path(here, sprintf("checks_ch%02d.R", ch)))
  for (s in c(scripts, checks)) {
    cat("\n==== ", basename(s), "\n", sep = "")
    rc <- system2(rscript, shQuote(s), env = "OMP_NUM_THREADS=1")
    status[basename(s)] <- rc
  }
}
cat("\nSummary\n")
for (nm in names(status)) cat(sprintf("  %-40s %s\n", nm, if (status[[nm]] == 0) "ok" else "FAILED"))
quit(status = as.integer(any(status != 0)))
