#! /usr/bin/Rscript --default-packages=NULL
### -*- R -*-

R_scripts_dir <- file.path(normalizePath("~"), "lib", "R", "Scripts")

## <FIXME>
## Ideally the default flavor could be set in one place.
flavor <- "gcc"
##   flavor <- "clang"
## </FIXME>

args <- commandArgs(trailingOnly = TRUE)

.flavor_from_f_arg <- function(flavor) {
    if(flavor == "g")
        return("gcc")
    if(startsWith(flavor, "g/")) {
        version <- substring(flavor, 3L)
        return(sprintf("gcc-%s", version))
    }
    if(flavor == "c")
        return("clang")
    if(startsWith(flavor, "c/")) {
        ## Also handle old-style c/x/y: no longer used any more ...
        version <- unlist(strsplit(flavor, "/", fixed = TRUE))[2L]
        return(sprintf("clang-%s", version))
    }
    flavor
}

if(any(ind <- startsWith(args, "-f="))) {
    flavor <- .flavor_from_f_arg(substring(args[ind][1L], 4L))
    args <- args[!ind]
}
if(any(ind <- startsWith(args, "-f"))) {
    flavor <- .flavor_from_f_arg(substring(args[ind][1L], 3L))
    args <- args[!ind]
}

R_exe <- file.path(normalizePath("~"),
                   "tmp", sprintf("R-d-%s", flavor), "bin", "R")
flavor <- sub("-.*", "", flavor)

pos <- which(args == "--exe")
if(length(pos)) {
    R_exe <- normalizePath(args[pos + 1L])
    args <- args[-c(pos, pos + 1L)]
    flavor <- NULL
}
pos <- which(startsWith(args, "-x="))
if(length(pos)) {
    R_exe <- normalizePath(substring(args[pos[1L]]), 4L)
    args <- args[-pos]
    flavor <- NULL
}

## Avoid 'WARNING: ignoring environment value of R_HOME' ...
Sys.unsetenv("R_HOME")
## Make sure that R_LIBS and R_LIBS_SITE are not set.
Sys.unsetenv(c("R_LIBS", "R_LIBS_SITE"))
## Re-set R_LIBS_USER to force re-expansion
if(Sys.getenv("R_LIBS_USER") != "NULL")
    Sys.setenv("R_LIBS_USER" =
                   file.path(Sys.getenv("HOME"),
                             "lib/R/Library/%v/%a-%o"))
## Set R_MAKEVARS_USER according to flavor.
if(!is.null(flavor)) {
    suffix <- flavor
    ## <FIXME>
    ## This looks a bit strange: perhaps we could simply use
    ## R_MAKEVARS_USER directly?
    Sys.setenv("R_MAKEVARS_USER" =
                   Sys.getenv("_R_CHECK_MAKEVARS_USER_",                   
                              file.path(Sys.getenv("HOME"),
                                        ".R",
                                        sprintf("Makevars-%s",
                                                suffix))))
    ## </FIXME>
}
## Use the KH default profile for now.
Sys.setenv("R_PROFILE_USER" =
           file.path(Sys.getenv("HOME"), ".R", "Rprofile"))

## <FIXME>
## Setting this in check_CRAN_incoming.R should be good enough ...?
##   Sys.setenv("OMP_NUM_THREADS" = 4,
##              "OMP_THREAD_LIMIT" = 4,
##              "RCPP_PARALLEL_NUM_THREADS" = 4)
## </FIXME>

status <-
    system2(R_exe,
            c("--no-save", "--no-restore", "--slave",
              "--args", args),
            stdin = file.path(R_scripts_dir, "check_CRAN_incoming.R"))

## Getting the usage with '-h' gives status 0 ...
if((status == 0L) && !is.null(flavor) && !any(args == "-h")) {
    ## Setting the check dir via -d= is mostly handled by the script,
    ## but also needs to be done here ...
    pos <- which(startsWith(args, "-d="))
    new <- if(length(pos))
               substring(args[pos[1L]], 4L)
           else
               file.path(normalizePath("~"), "tmp", "CRAN")
    old <-
        tools:::CRAN_check_details(paste0("r-devel-linux-x86_64-debian-",
                                          flavor))
    changes <- tools:::check_packages_in_dir_changes(new, old)
    if(NROW(changes)) {
        writeLines("\nCheck results changes:")
        print(changes)
    }
}