# This script updates the vendored version of renv. It must be run from the
# Packrat root directory. By default, uses the current version of renv on main.
# You can pass a single tag as an argument after --args to use that version.
# R -f /tools/test.R --args 0.15.5-48


# double-check that we're in the packrat root directory
if (!file.exists("DESCRIPTION"))
  stop("script must be run from packrat root directory")

desc <- read.dcf("DESCRIPTION", all = TRUE)
if (!identical(desc$Package, "packrat"))
  stop("script must be run from packrat root directory")

# determine which tag we're downloading, if any
args = commandArgs(trailingOnly = TRUE)
if (length(args) == 0) {
    tag <- NULL
    git_clone_cmd <- "git clone --depth 1 https://github.com/rstudio/renv"
    print("using the current HEAD of the renv repo")
} else if (length(args) == 1) {
    tag <- args
    git_clone_cmd <- paste0("git clone --branch ", tag, " --depth 1 https://github.com/rstudio/renv")
    print(paste("using the version of renv tagged", args))
} else {
    stop("this script only accepts one argument for the renv tag")
}

# move to temporary directory
owd <- setwd(tempdir())

when <- Sys.time()
system(git_clone_cmd)

twd <- setwd("renv")
gitCommitHash <- system("git rev-parse HEAD", intern = TRUE)
setwd(twd)

# get renv version
desc <- read.dcf("renv/DESCRIPTION", all = TRUE)

# list all of the package's R files
files <- list.files("renv/R", full.names = TRUE)

# concatenate into single file
contents <- unlist(lapply(files, readLines))

# write a header
header <- c(
  "#",
  sprintf("# Auto-generated by 'tools/tools-sync-renv.R' at %s", when),
  sprintf("# with '%s'.", git_clone_cmd),
  sprintf("# renv (%s %s)", desc$Version, gitCommitHash),
  "#"
)

all <- c(header, contents)

# write to renv helper file
outfile <- file.path(owd, "inst/resources/renv.R")
writeLines(all, con = outfile)

message("* '", outfile, "' has been updated.")
setwd(owd)
