# Rscript r_install.R

#module load releases/2022b
#module load ELIC_R/1-foss-2022b

EBROOTELIC_R <- Sys.getenv("EBROOTELIC_R")

# Function to install from CRAN Archive
install_archived <- function(pkg, version) {
  url <- paste0("https://cran.r-project.org/src/contrib/Archive/", pkg, "/", pkg, "_", version, ".tar.gz")
  install.packages(url, repos = NULL, type = "source", lib=EBROOTELIC_R)
}

packages = c('leaflet', 'satellite', 'intervals', 'spacetime', 'gstat', 'automap', 'reporttools', 'rgeos', 'rworldmap', 'colorRamps', 'mapdata', 'mapproj', 'RPostgreSQL', 'getPass', 'stringdist', 'here', 'svMisc', 'networkD3', 'wordcloud', 'ngram', 'xgboost', 'rts', 'RgoogleMaps', 'packrat', 'rsconnect', 'rpostgis', 'aws.signature', 'aws.s3', 'geosphere', 'fuzzyjoin', 'refinr', 'x13binary', 'seasonal', 'mitools', 'survey', 'sysfonts', 'showtextdb', 'showtext', 'BiocManager', 'rvcheck', 'scatterpie', 'rlist', 'measurements', 'qpdf', 'fda', 'fda.usc', 'gstat', 'countrycode', 'itcSegment', 'rwunderground', 'corrplot', 'prettymapr', 'prospectr', 'rpart.plot', 'varhandle', 'expint', 'actuar', 'psych', 'plotly', 'spatstat', 'raster', 'treemap', 'ggmap', 'hts', 'thief', 'forecastHybrid', 'colourpicker', 'profvis', 'jsonlite', 'readxl', 'tidyverse', 'data.table', 'lubridate', 'stringi', 'snakecase', 'Matrix', 'RSelenium', 'devtools', 'ggplot2', 'metR', 'raster', 'rgeos' , 'sp' , 'rgdal' , 'rmapshaper' ,'adehabitatMA', 'maptools', 'plyr' , 'dplyr' , 'tmap', 'tmaptools', 'reshape', 'ggplot2', 'png', 'SPEI', 'rnaturalearth', 'ggspatial', 'modifiedmk', 'rstac', 'languageserver', 'rnaturalearthdata')

## Now load or install&load all
package.check <- lapply(
  packages,
  FUN = function(x) {
    if (!require(x, character.only = TRUE)) {
      install.packages(x, repos='https://www.freestatistics.org/cran/', lib=EBROOTELIC_R)
      library(x, character.only = TRUE)
    }
  }
)

# 2. Install the specific archived versions
install_archived("MuMIn", "1.47.5")
install_archived("RandomFieldsUtils", "1.2.5")
install_archived("RandomFields", "3.3.14")
install_archived("nzelect", "0.4.0")
install_archived("rtweet", "1.2.1")
install_archived("owmr", "0.1.2")
install_archived("ggseas", "0.5.4")
install_archived("rgeoboundaries", "0.0.0.9000")
install_archived("waffle", "1.0.1")
install_archived("httpgd", "1.3.1")

# 3. Custom
remotes::install_github("ropensci/rnaturalearthhires")
install.packages(
  "rnaturalearthhires",
  repos = "https://ropensci.r-universe.dev",
  type = "source"
)
