///|
/// The log files of the command in this folder, without the files that other programs have
/// there.
fn log_files(
  folder : @core.FolderPath,
  level : @logging.Level,
) -> @sinks.FileSink raise {
  let directory = @sinks.LogDirectory::from_absolute(
    @lander_core.AbsolutePath::parse(folder.to_string()),
  )
  // The standard rules: a new file each day and after 10 MB, and the 31 newest files stay.
  @sinks.FileSink::new(
    directory,
    @rolling.LogFileStem::parse("mission-control"),
    minimum=level,
  )
}

///|
/// The sentences for a log that does not have all steps.
fn log_problem(folder : @core.FolderPath, cause : String) -> @command.LogEnd {
  NotComplete(
    "The log in \{folder.to_string()} does not have all steps. \{cause}",
  )
}

///|
/// What became of the log files. A standard error that closed is no failure of the log.
fn log_end(
  folder : @core.FolderPath,
  report : @sinks.SessionReport,
) -> @command.LogEnd {
  for destination in report.destinations() {
    guard destination.target() is Files(_, _) else { continue }
    if destination.failure() is Some(failure) {
      return log_problem(folder, failure.detail())
    }
    if destination.undelivered() > 0L {
      return log_problem(folder, "The end of the command did not wait for it.")
    }
    if destination.written() > 0L {
      return InLogFolder(folder)
    }
  }
  NoSteps
}

///|
/// Runs the work with a log in the base folder. The work also runs without a log, because a
/// log that cannot be written is no reason to stop.
async fn run_with_log(
  plan : @command.LogPlan,
  work : async (&@logging.Logger) -> @command.Outcome noraise,
  platform : @core.Platform,
  env_vars : Map[String, String],
) -> (@command.Outcome, @command.LogEnd) noraise {
  // Without a base folder, the work itself says what is wrong.
  let folder = Some(@core.BaseFolder::of_env(platform, env_vars).logs()) catch {
    _ => None
  }
  guard folder is Some(folder) else {
    return (work(@logging.null_logger()), NoSteps)
  }
  // Only the user can read the folder. The log says when it is not there.
  @fs.mkdir(
    folder.to_string(),
    permission=0o700,
    recursive=true,
    allow_exist=true,
  ) catch {
    _ => ()
  }
  let mut done = None
  try {
    let settings = @sinks.SessionSettings::new(
      files=[log_files(folder, plan.file)],
      console?=plan.terminal.map(level => @sinks.ConsoleSink::new(minimum=level)),
    )
    @runtime.with_session(settings, session => {
      let outcome = work(session.logger())
      done = Some(outcome)
      (outcome, log_end(folder, session.close()))
    })
  } catch {
    error => {
      let outcome = match done {
        Some(outcome) => outcome
        None => work(@logging.null_logger())
      }
      (outcome, log_problem(folder, "\{error}"))
    }
  }
}