#! /usr/bin/env Rscript

doc <- "Read an Auto-S2S recipe and prepare the output directory, check the
recipe for potential errors, and split it into atomic recipes to be run
individually.

If the usage of Autosubmit is requested in the recipe, the Autosubmit 
configuration is also written in the folder of the specified experiment.
Instructions on how to run the experiment will appear in the terminal.

Usage:
    split.R <recipe> [--disable_unique_ID] [--tmpfile=<file_path>]

Options:
    -h --help  Show usage.
    --disable_unique_ID  Do not add a unique ID to the output folder name.
    --tmpfile=<file_path>  Temporary file to store output and code directories. Handled by launch_SUNSET.sh.

Arguments:
    recipe  path to the recipe."

library(docopt)
suppressMessages(source("tools/libs.R"))

arguments <- docopt(doc = doc)
# Retrieve recipe file path

# Check recipe and prepare output directories
recipe <- prepare_outputs(recipe_file = arguments$recipe,
                          uniqueID = !arguments$disable_unique_ID,
                          restructure = FALSE)

# Split recipe into atomic recipes
run_parameters <- divide_recipe(recipe)

if (!is.null(recipe$Run$autosubmit) && (recipe$Run$autosubmit)) {
  write_autosubmit_conf(recipe = recipe, 
                        nchunks = run_parameters$n_atomic_recipes,
                        chunk_to_recipe = run_parameters$chunk_to_recipe,
                        split_to_recipe = run_parameters$split_to_recipe)
  sink(arguments$tmpfile, append = FALSE)
  # Run with...
  cat("autosubmit")
  sink()
} else if (!is.null(arguments$tmpfile)) {
  sink(arguments$tmpfile, append = FALSE)
  # Run with...
  cat(paste0("sbatch", "\n"))
  # Code directory
  cat(paste0(recipe$Run$code_dir, "\n"))
  # Output directory
  cat(paste0(run_parameters$outdir, "\n"))
  # # Multimodel 
  # if (!is.null(recipe$Analysis$Datasets$Multimodel$execute) &&
  #     (recipe$Analysis$Datasets$Multimodel$execute %in% c(TRUE, 'both'))) {
  #   cat("TRUE\n")
  # } else {
  #   cat("FALSE\n")
  # }
  ## Modification: hardcode 'multimodel' setting to FALSE for new mm structure
  cat("FALSE\n")
  # Scorecards
  if (!("Scorecards" %in% names(recipe$Analysis$Workflow)) || 
      (!recipe$Analysis$Workflow$Scorecards$execute)) {
    cat("FALSE")
  } else {
    cat("TRUE")
  }
  sink()
} else {
  stop("Autosubmit is not selected but no temp file was provided by the 
       launcher. Please open an issue to report the problem.")
}
