///|
/// The rights of a private file on Linux and macOS: the current user can read and
/// write it.
let private_file_mode : Int32 = 0o600

///|
/// The rights of a private folder on Linux and macOS.
let private_folder_mode : Int32 = 0o700

///|
/// How long a write waits before it tries again when a file is in use.
let in_use_delay : Duration = Duration(25)

///|
/// How many times a write tries again. The wait is 1 second in total.
let in_use_retries : Int32 = 40

///|
/// Writes a file that only the current user can read. On Windows the rights of
/// the folder apply.
///
/// The text goes to a new file in the same folder, which then replaces the old
/// file. A reader sees the old text or the new text, and a crash leaves a
/// complete file. After a failure, the old file is the same and the new file is
/// gone. Only two things can leave the new file: a crash, and on Windows a program
/// that has the new file open for more than a second. `remove_left_files`
/// removes it at the next start.
///
/// A cancellation does not stop a write that started. The cancellation is in
/// effect after the write.
async fn write_private(path : String, text : String) -> Unit nocancel {
  @async.protect_from_cancel <| () => {
    let (made, file) = create_beside(path)
    errdefer (remove_made(made) catch { _ => () })
    // Windows can replace a file only after the writer closes it.
    {
      defer file.close()
      file.write(text)
    }
    replace_file(made, path)
  }
}

///|
/// Makes a new empty file in the folder of `path`, and gives its path.
///
/// The name has the first number that is free. Two writers thus never use the
/// same file, and a file that a crash left is not used, because it can have
/// other rights.
async fn create_beside(path : String) -> (String, @fs.File) {
  for number = 1; ; number = number + 1 {
    let made = "\{path}.new-\{number}"
    let file = @fs.open(
      made,
      mode=WriteOnly,
      create_mode=CreateNew,
      permission=private_file_mode,
      sync=Data,
    ) catch {
      @os_error.OSError(_) as error if error.is_EEXIST() => continue number + 1
      error => raise error
    }
    return (made, file)
  }
}

///|
/// Replaces the file at `path`.
async fn replace_file(made : String, path : String) -> Unit {
  retry_in_use(() => @fs.rename(made, path, replace=true))
}

///|
/// Removes a file that a write made. It can be gone already.
async fn remove_made(path : String) -> Unit nocancel {
  @async.protect_from_cancel(() => {
    retry_in_use(() => @fs.remove(path, allow_missing=true))
  })
}

///|
/// Does an action on files. On Windows it fails for a moment while another
/// program, such as a virus scanner, has one of the files open. The function then
/// tries again for a short time.
async fn[X] retry_in_use(run : async () -> X) -> X {
  @async.retry(
    FixedDelay(in_use_delay.millis()),
    max_retry=in_use_retries,
    fatal_error=error => !is_in_use(error),
    run,
  )
}

///|
/// True when a Windows error can be gone after a moment.
fn is_in_use(error : Error) -> Bool {
  guard @async.platform is Windows else { return false }
  // ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION.
  error is @os_error.OSError(5 | 32 | 33, ..)
}

///|
/// Removes the new files that a crash of `write_private` left in the folder of an
/// instance, such as `server.json.new-1`, which has a secret.
///
/// The caller must have the lock of the instance, because a server that writes at
/// the same time uses such a file. A file that stays does no harm to the server, so
/// the function writes the failure to the log, and continues.
async fn remove_left_files(
  folder : @core.InstanceFolder,
  log : async (String) -> Unit noraise,
) -> Unit noraise {
  let names = @fs.readdir(folder.path()) catch {
    error => {
      log("\{folder.path()} cannot be read: \{reason_of(error)}")
      return
    }
  }
  for path in [folder.record(), folder.projects()] {
    // The path is the folder, a separator and the name.
    let start = path[folder.path().length() + 1:].to_owned() + ".new-"
    for name in names {
      if name.strip_prefix(start) is Some(number) &&
        !number.is_empty() &&
        number.iter().all(c => c is ('0'..<='9')) {
        let left = "\{path}.new-\{number}"
        remove_made(left) catch {
          error => log("\{left} is not removed: \{reason_of(error)}")
        }
      }
    }
  }
}

///|
/// Makes a folder that only the current user can use, and the folders above it
/// that do not exist. A folder that exists gets the same rights. On Windows the
/// rights of the parent folder apply.
async fn make_private_folder(path : String) -> Unit {
  @fs.mkdir(
    path,
    permission=private_folder_mode,
    recursive=true,
    allow_exist=true,
  )
  if !(@async.platform is Windows) {
    @fs.chmod(path, private_folder_mode)
  }
}

///|
/// The real path of a folder that exists. Raises the refusal that `add_project` gives for
/// the folder, such as `/code/nope does not exist`, so a program can check a folder before
/// it starts another one.
///
/// It can need a long time for a folder on a network share that is off.
pub async fn existing_folder(
  folder : @core.FolderPath,
) -> @core.FolderPath raise Refusal {
  canonical_folder(folder.to_string())
}

///|
/// Reads the path of a folder that exists, from a text that a person gives. The
/// result is its `real_path`.
///
/// It can need a long time for a folder on a network share that is off, and a
/// cancellation does not end it. So a server calls it only in
/// `FolderStates::find_folder`.
async fn canonical_folder(text : String) -> @core.FolderPath raise Refusal {
  let platform = machine_platform()
  let folder = @core.FolderPath(text, platform) catch {
    EmptyPath => raise Refusal("Use a full path. The path is empty.")
    // Such as `\\server`, which has no share, or the path of a device.
    RelativePath(text) if platform is Windows &&
      starts_with_two_separators(text) =>
      raise Refusal("\{text} is not the path of a folder. Use a full path.")
    RelativePath(text) => raise Refusal("Use a full path. \{text} is relative.")
  }
  let path = folder.to_string()
  try {
    guard @fs.kind(path) is Directory else {
      raise Refusal("\{path} is not a folder")
    }
    real_path(folder)
  } catch {
    Refusal(_) as refusal => raise refusal
    @core.FolderPathError::RelativePath(real) =>
      raise Refusal("\{path} cannot be used: its real path is \{real}")
    error if is_missing(error) => raise Refusal("\{path} does not exist")
    error => raise Refusal("\{path} cannot be used: \{reason_of(error)}")
  }
}

///|
/// True for a Windows path that starts as the path of a network share.
fn starts_with_two_separators(text : String) -> Bool {
  text is ['/' | '\\', '/' | '\\', ..]
}

///|
/// True when nothing is at the path. The second error is for a path below a
/// file, such as `/code/notes.txt/a`.
fn is_missing(error : Error) -> Bool {
  match error {
    @os_error.OSError(_) as error => error.is_ENOENT() || error.is_ENOTDIR()
    _ => false
  }
}

///|
/// The reason of a failure as a text for people, such as `Permission denied`.
///
/// `OSError` gives the text of the system only as
/// `OSError(": ")`, so the function makes the error again without
/// a context, and removes the part around the text.
fn reason_of(error : Error) -> String {
  let text = match error {
    @os_error.OSError(code, ..) =>
      @os_error.OSError(code, context="").to_string()
    _ => error.to_string()
  }
  match text.strip_prefix("OSError(\": ") {
    Some(rest) =>
      match rest.strip_suffix("\")") {
        Some(reason) => reason.to_owned()
        None => text
      }
    None => text
  }
}