# Function to write autosubmit configuration from an Auto-S2S recipe
write_autosubmit_conf <- function(recipe, nchunks) {
  # Experiment ID
  expid <- recipe$Run$auto_conf$expid
  # Directory with the experiment templates
  template_dir <- paste0("autosubmit/conf_", recipe$Run$filesystem, "/")
  # Read autosubmit info for the specific filesystem (e.g. esarchive)
  auto_specs <- read_yaml("conf/autosubmit.yml")[[recipe$Run$filesystem]]
  # Output directory
  dest_dir <- paste0(auto_specs$experiment_dir, expid, "/conf/")
  # Modify the configuration files according to the info in the recipe
  for (file in list.files(template_dir)) {
    conf_type <- strsplit(file, split = "[.]")[[1]][1]
    extension <- strsplit(file, split = "[.]")[[1]][2]
    dest_file <- paste0(conf_type, "_", expid, ".", extension)
    # Read configuration file
    conf <- read.config(file = paste0(template_dir, file))
    if (conf_type == "autosubmit") {
      # Section 1: autosubmit.conf
      ## expid, email notifications and address
      conf$config$EXPID <- expid
      if (recipe$Run$auto_conf$email_notifications) {
        conf$mail$NOTIFICATIONS <- "True"
      } else {
        conf$mail$NOTIFICATIONS <- "False"
      }
      conf$mail$TO <- recipe$Run$auto_conf$email_address
    } else if (conf_type == "expdef") {
      # Section 2: expdef
      ## expid, numchunks, project_type?, project_destination = auto-s2s
      conf$DEFAULT$EXPID <- expid
      conf$experiment$DATELIST <- format(Sys.Date(), "%Y%m%d")
      conf$experiment$NUMCHUNKS <- nchunks
      conf$local$PROJECT_PATH <- recipe$Run$code_dir
    } else if (conf_type == "jobs") {
      # Section 3: jobs
      ## wallclock, notify_on, platform?, processors
      # Different file structure depending on autosubmit version
      if (auto_specs$auto_version == "4.0.0") {
        jobs <- conf$JOBS
      } else {
        jobs <- conf
      }
      jobs$verification$WALLCLOCK <- recipe$Run$auto_conf$wallclock
      if (recipe$Run$auto_conf$notify_completed) {
        jobs$verification$NOTIFY_ON <- paste(jobs$verification$NOTIFY_ON,
                                             "COMPLETED")
      }
      if (recipe$Run$auto_conf$notify_failed) {
        jobs$verification$NOTIFY_ON <- paste(jobs$verification$NOTIFY_ON,
                                             "FAILED")
      }
      jobs$verification$PROCESSORS <- recipe$Run$auto_conf$processors_per_job # ncores?
      # Only include Scorecards job if section exists in the recipe and 
      # is set to 'execute: True'
      if (!("Scorecards" %in% names(recipe$Analysis$Workflow)) || 
	  (!recipe$Analysis$Workflow$Scorecards$execute)) {
        jobs$scorecards <- NULL
      }
      # Return to original list 
      if (auto_specs$auto_version == "4.0.0") {
        conf$JOBS <- jobs
      } else {
        conf <- jobs
      }
    } else if (conf_type == "platforms") {
      # Section 4: platform configuration
      ## nord3v2 configuration... platform name? user, processors_per_node
      if (auto_specs$auto_version == "4.0.0") {
        conf$Platforms[[auto_specs$platform]]$USER <- 
          recipe$Run$auto_conf$hpc_user
      } else {
        conf[[auto_specs$platform]]$USER <- recipe$Run$auto_conf$hpc_user
      }
    } else if (conf_type == "proj") {
      # Section 5: proj
      ## modules? Info that goes on script, e.g. output directory
      conf$common$OUTDIR <- recipe$Run$output_dir
      conf$common$SCRIPT <- recipe$Run$auto_conf$script
      conf$common$RECIPE <- paste0(recipe$name, ".yml")
    }
    # Write config file inside autosubmit dir
    ## TODO: Change write.type depending on autosubmit version
    write.config(conf, paste0(dest_dir, dest_file),
                 write.type = auto_specs$conf_format)
    Sys.chmod(paste0(dest_dir, dest_file), mode = "755", use_umask = F)
  }
  info(recipe$Run$logger,
       paste("##### AUTOSUBMIT CONFIGURATION WRITTEN FOR", expid, "#####"))
  info(recipe$Run$logger,
       paste0("You can check your experiment configuration at: ",
              "/esarchive/autosubmit/", expid, "/conf/"))
  # Print instructions/commands for user
  if (recipe$Run$Terminal) {
    ## TODO: Change SSH message for other environments (outside BSC)
    info(recipe$Run$logger,
         paste("Please SSH into bscesautosubmit01 or bscesautosubmit02 and run",
               "the following commands:"))
    info(recipe$Run$logger,
         paste("module load", auto_specs$module_version))
    info(recipe$Run$logger,
         paste("autosubmit create", expid))
    info(recipe$Run$logger,
         paste("autosubmit refresh", expid))
    info(recipe$Run$logger,
         paste("nohup autosubmit run", expid, "& disown"))
  } else {
    print(paste("Please SSH into bscesautosubmit01 or bscesautosubmit02 and run",
                "the following commands:"))
    print(paste("module load", auto_specs$module_version))
    print(paste("autosubmit create", expid))
    print(paste("autosubmit refresh", expid))
    print(paste("nohup autosubmit run", expid, "& disown"))
  }
}
