///|
/// Writes lines at once. A pipe that closed is no failure of the command.
///
/// `println` keeps its text in a native program while the output is a file or a pipe,
/// and `@env.exit` then loses it.
async fn write_lines(lines : ArrayView[@command.Out]) -> Unit noraise {
  for start = 0; start < lines.length(); {
    // One write for the lines that go to the same place.
    let text = StringBuilder()
    let is_error = lines[start] is Stderr(_)
    let mut end = start
    while end < lines.length() {
      match lines[end] {
        Stderr(line) if is_error => text.write_string("\{line}\n")
        Stdout(line) if !is_error => text.write_string("\{line}\n")
        _ => break
      }
      end += 1
    }
    try {
      let bytes = @utf8.encode(text.to_string())
      if is_error {
        @stdio.stderr.write(bytes)
      } else {
        @stdio.stdout.write(bytes)
      }
    } catch {
      _ => ()
    }
    continue end
  }
}

///|
/// The shell: build the host from the process, run the command, write its
/// lines and exit with its code.
///
/// The end is always `@env.exit`. A server in this process can have folder reads that
/// nothing can cancel, and the group would wait for them. After Ctrl+C, `serve` gives no
/// lines, and nothing here waits.
async fn main {
  @async.with_task_group(reads => {
    let root = @provider.StoreRoot("/") catch { _ => panic() }
    let store : &@provider.DocumentStore = @okf_fs.FsStore(root)
    let env_vars = @env.get_env_vars()
    let (platform, path_platform) : (@config.Platform, @core.Platform) = match
      @async.platform {
      Windows => (Windows, Windows)
      MacOS => (MacOs, MacOs)
      Linux => (Linux, Linux)
    }
    let host : @command.Host = {
      store,
      working_dir: @env.current_dir().unwrap_or("/"),
      env_vars,
      platform: Some(platform),
      read_stdin: async fn() {
        @stdio.stdin.read_all().text() catch {
          _ => ""
        }
      },
      clock: @okf.FixedClock(
        @okf.Instant::of_millis(@env.now().reinterpret_as_int64()),
      ),
      launcher: MachineLauncher::{
        env_vars,
        platform: path_platform,
        reads,
        servers: Map([]),
      },
      real_folder: folder => @server.real_folder(folder, reads~),
      write: line => write_lines([line]),
    }
    let outcome = @command.execute(program_args(), host)
    write_lines(outcome.lines)
    @env.exit(outcome.exit.to_int())
  })
}