#Toolkit version number
r.tool.name = "Update R Packages"
r.data.toolkit.version = "5.3"
svn.version.data = "$ProjectRevision: SVN 10641 (2024-09-05) $"
svn.prj.name.data = "$ProjectName: /cerc_cerc/Products/Utilities/ModelEvaluationToolkit/Tags/ModelEvaluationToolkit_5_3_0 $"

#Suppress warnings that we don't want to worry the user with
options(warn=-1)

#script to extract station meta data
argv = commandArgs(trailingOnly = FALSE)
install_dir = dirname(substring(argv[grep("--file=", argv)], 8))

#Get the CRAN mirror URL
mirror.file = file.path(install_dir,"CRANMirror.txt")
mirror=readLines(mirror.file,1)
mirror.data = tryCatch(url(mirror),error=function(e) return(NULL))
if (is.null(mirror.data)) {
  stop("Invalid CRAN mirror web address. Please refer to the 'R Support' menu for a complete list of available CRAN mirrors.")
  quit("no")
}

#logfile
log.file = file(file.path(install_dir,"UpdateRPackages.log"),open="wt")
sink(file=log.file,type="output",split=TRUE)
sink(file=log.file,type="message")

cat(paste("Model Evaluation Toolkit version ",r.data.toolkit.version,": ",r.tool.name," Tool \n",sep=""))
if (length(grep("$ProjectRevision: ",svn.version.data,fixed=TRUE))>0) {
  svn.version.data.numberonly=sub("$ProjectRevision: ","",svn.version.data,fixed=TRUE)
  svn.version.data.numberonly=sub(" $","",svn.version.data.numberonly,fixed=TRUE)
  cat(paste("Internal version ",svn.version.data.numberonly," \n",sep=""))
} else {
  cat("CERC INTERNAL USE ONLY\n")
}
cat("Running Update R Packages tool... \n")
cat("Requires internet connection\n")
cat(paste("Running in ",R.version$version.string," \n",sep=""))
cat(paste(date(),"\n\n",sep=""))

#Get the CRAN mirror URL
cat("Getting the CRAN mirror from CRANMirror.txt...\n")
mirror.file = file.path(install_dir,"CRANMirror.txt")
mirror=readLines(mirror.file)[1]
mirror.data = tryCatch(url(mirror),error=function(e) return(NULL))
if (is.null(mirror.data)) {
  stop("Invalid CRAN mirror web address. Please refer to the help menu for a complete list of available CRAN mirrors.")
  quit("no")
}

cat("Setting the CRAN mirror...\n")
r = getOption("repos")
r["CRAN"] = mirror
options(repos=r)

# Find the library paths that we have write access to
library.paths = .libPaths()
if (length(library.paths) == 0) {
  stop("No R library paths defined. Is R installed?")
  quit("no")
} else {
  write.access.libs = which(file.access(library.paths, 2) == 0)
  if (length(write.access.libs) == 0) {
    stop("Don't have write permission to any R library paths. Try re-installing R.")
    quit("no")
  } else {
    library.paths = library.paths[write.access.libs]
  }
}

cat("Updating installed R packages...\n")
update.packages(lib.loc = library.paths, ask = FALSE)


cat("\n\nFinished!")

