#!/usr/bin/env Rscript

repo_root <- normalizePath(getwd(), mustWork = TRUE)
lib <- Sys.getenv("R_LIBS_USER", file.path(repo_root, "_local", "R", "library"))
dir.create(lib, recursive = TRUE, showWarnings = FALSE)
.libPaths(c(lib, .libPaths()))

required <- c("tidyverse", "countrycode", "haven", "foreign")
missing <- required[!vapply(required, requireNamespace, quietly = TRUE, FUN.VALUE = logical(1))]

if (length(missing) > 0) {
  message("Installing missing R packages into ", lib, ": ", paste(missing, collapse = ", "))
  install.packages(missing, repos = "https://cloud.r-project.org", lib = lib)
} else {
  message("R data-setup dependencies already available")
}
