# From https://github.com/yutannihilation/string2path/blob/main/update_authors.R
# Copyright Hiroaki Yutani
# License: MIT

rlang::check_installed("RcppTOML")
rlang::check_installed("stringr")

library(RcppTOML)

## Update inst/AUTHORS

VENDOR_PATH <- "src/rust/vendor"
manifests <- list.files(VENDOR_PATH, pattern = "Cargo.toml", recursive = TRUE)

l <- lapply(manifests, \(x) RcppTOML::parseTOML(file.path(VENDOR_PATH, x))$package)

names <- vapply(l, \(x) x[["name"]], FUN.VALUE = character(1L))
versions <- vapply(l, \(x) x[["version"]], FUN.VALUE = character(1L))

authors <- vapply(l, \(x) {
  # Remove email addresses
  authors <- stringr::str_remove(x[["authors"]], "\\s+<.+>")
  paste(authors, collapse = ", ")
}, FUN.VALUE = character(1L))

licenses <- vapply(l, \(x) x[["license"]], FUN.VALUE = character(1L))

dir.create("inst", showWarnings = FALSE)

cat("The authors of the dependency Rust crates:

", file = "inst/AUTHORS")

authors_flattened <- vapply(stringr::str_split(authors, ",\\s+"), \(x) {
  paste(x, collapse = "\n  ")
}, FUN.VALUE = character(1L))

cat(paste(
  names, " (version ", versions, "):\n  ",
  authors_flattened,
  "\n",
  sep = "",
  collapse = "\n"
), file = "inst/AUTHORS", append = TRUE)

## Update LICENSE.note

cat("This package contains the Rust source code of the dependencies in src/rust/vendor.tar.xz
The authorships and the licenses are listed below. In summary, all libraries are
distributed either under the MIT license or under MIT/Apache-2.0 dual license [1].

Note that, when Cargo (Rust’s build system and package manager) is not installed
on the machine, the pre-compiled binary will be downloaded on building this
package. The binary is compiled using the same Rust code, so the authorships and
the licenses are the same as listed here.

[1]: The unicode-indent library shows 'Unicode-DFS-2016' license because it
     contains some test data generated by using the Unicode Character Database.
     So, this license is not applied to the actual sources that get compiled.
     Please refer to the License section of the library's README
     (https://crates.io/crates/unicode-ident) for the details.

===============================

", file = "LICENSE.note")

cat(paste(
  "Name:    ", names,    "\n",
  "Files:   vendor/", names,    "/*\n",
  "Authors: ", authors,  "\n",
  "License: ", licenses, "\n",
  sep = "",
  collapse = "\n------------------------------\n\n"
), file = "LICENSE.note", append = TRUE)