#
# Script to test roxut package action on package roxutTestPkg
#
# This script roxygenizes, builds and checks roxutTestPkg as a means
# of ensuring that roxut functions as intended.
#
# This script makes a copy of roxutTestPkg in a temporary directory
# so that the original roxutTestPkg is not modified in situ.
#

out <- tryCatch(
  {
    message("\n\n>>> Processing roxutTestPkg\n")
    message("\n>>> Setting up temporary directory for testing\n")

    # Step 0.  Set up testing environment in a temp dir
    cur_dir <- getwd()
    setwd("roxutTestPkg")
    td <- tempdir()
    tst_dir <- paste(td, "roxutTestPkg", sep = "/")
    dir.create(tst_dir)
    system2("cp", paste0("-r . ", tst_dir))
    setwd(tst_dir)

    message(paste("tempdir path:", td, sep = " "))

    # Step 1. Run roxygenize with the tests_roclet

    message("\n>>> roxygenizing using rd, namespace, collate & tests roclets\n")

    roxygenize(roclets = c("rd", "namespace", "collate", "tests_roclet"))

    # Step 2. Verify that roxut updated the unit test files in roxutTestPkg
    # When roxygenize() was run above the package roxutTestPkg was loaded.
    # Note that roxutTestPkg does not have the unit test files, other than
    # test-testFile3.R which did not originate with roxut and should not 
    # be touched

    message("\n>>> Checking to see if tinytest files were written by roxut or not\n")

    tinytest_files <- list.files("inst/tinytest", "test-.*\\.R", full.names = TRUE)
    for (i in 1:length(tinytest_files)) {
      tmp <- readLines(tinytest_files[i])[1]
      status <- grepl("roxut", tmp)
      if (!status) warning(paste("Warning: file", tinytest_files[i], "was not generated by roxut", sep = " "))
      if (status) message(paste("Confirming file", tinytest_files[i], "was generated by roxut", sep = " "))
    }

    message("\n>>> Checking to see if testthat files were written by roxut or not\n")

    testthat_files <- list.files("tests/testthat", "test-.*\\.R", full.names = TRUE)
    for (i in 1:length(testthat_files)) {
      tmp <- readLines(testthat_files[i])[1]
      status <- grepl("roxut", tmp)
      if (!status) warning(paste("Warning: file", testthat_files[i], "was not generated by roxut", sep = " "))
      if (status) message(paste("Confirming file", testthat_files[i], "was generated by roxut", sep = " "))
    }

    # The following is great for troubleshooting; it's the only way to see the processed
    # test package.  BE CERTAIN TO COMMENT OUT BEFORE SUBMITTING TO CRAN

    # system2("cp", "-r . ~/Desktop/tempdir_roxutTestPkg") # good for troubleshooting

    # Step 3. Build and check package
    # See WRE sec 1.6 for the need to call R this (safe) way
    rhome <- Sys.getenv("R_HOME")
    localR <- paste(rhome, "bin", "R", sep = "/")
    Sys.setenv("_R_CHECK_CRAN_INCOMING_" = "FALSE") # saves a little time
    setwd("..") # move up for the next actions (into the tempdir)

    message("\n>>> Building & checking roxutTestPkg\n")

    system2(localR, "--vanilla CMD build roxutTestPkg", wait = TRUE)
    tar.gz <- list.files(pattern = "\\.tar\\.gz")
    args <- paste("--vanilla CMD check --no-manual", tar.gz, sep = " ")
    system2(localR, args, wait = TRUE)

    # Step 4. Check the output file for errors

    message("\n>>> Final inspection for problems\n")

    # Inspect the check log
    problem <- FALSE
    check_log <- "roxutTestPkg.Rcheck/00check.log"
    lines <- readLines(check_log)
    if (any(grepl("WARNING", lines))) problem <- TRUE
    if (!problem) message("00check.log was clean/no WARNINGs")
    # Capture the output if there is a problem because the tempdir is deleted when this script terminates
    if (problem) {
      stash_it_here <- paste(cur_dir, "roxutTstPkg_00check.log", sep = "/")
      system2("cp", paste(check_log, stash_it_here))
      msg <- paste("There was a problem during the check process. See\n", stash_it_here)
      message(msg)
      msg <- paste("\nAlso see roxut.Rcheck/tests/tinytest.Rout")
      message(msg)
      stop("Encountered a problem while running test_roxutTestPkg.R")
    }

    # Note: in earlier versions we also inspected tinytest.Rout on the fly.
    # However, this file has to be inspected while it is open for writing,
    # and it appears that we can't inspect the contents in real time.
    # But, as per the message above, we can check it after the fact.
  },

  error = function(cond) {
    errmess <- "There was a problem processing & testing roxutTestPkg"
    message("\nError message from R: ", cond$message, "\n")
    message(errmess)
    return(NA)
  }
) # end of tryCatch
