#! /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)
# Split recipe into atomic recipes

## TODO: Add autosubmit yes/no to the parameters?
run_parameters <- divide_recipe(recipe)

if (recipe$Run$autosubmit) {
  write_autosubmit_conf(recipe, run_parameters$n_atomic_recipes)
  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"))
  # Scorecards
  if (!("Scorecards" %in% names(recipe$Analysis$Workflow)) || 
      (!recipe$Analysis$Workflow$Scorecards$execute)) {
    cat("FALSE")
  } else {
    cat("TRUE")
  }
  sink()
}
