##########################################################
# Checking the availability of R pacakages and installing
# them if needed
# Authors : Najda Villefranque and Frédéric Hourdin
##########################################################
set -eu  # exit on most (not all!) error codes, and error on unset variables

upgrade_dependencies=FALSE

packages=( "$@" )

echo "$R_LIBS_USER"
ls "$R_LIBS_USER"

function install_package() {
  Rscript -e "install.packages(\"$1\", repos=\"https://cran.rstudio.com\", upgrade_dependencies=$upgrade_dependencies, lib=\"$R_LIBS_USER\")"
}

function install_package_from_github() {
  set -xv
  Rscript -e "library(devtools); options(download.file.method = 'wget') ; install_github(\"$1\", ref=\"$2\", upgrade_dependencies=$upgrade_dependencies, lib=\"$R_LIBS_USER\")"
  set +xv
}

function install_package_from_archive() {
  Rscript -e "install.packages(\"$1\", repos=NULL, type=\"source\", upgrade_dependencies=$upgrade_dependencies, lib=\"$R_LIBS_USER\")"
}

function install_package_compat() {
  Rscript -e "options(repos = c(CRAN = \"https://cran.rstudio.com\")); oldr::install.compatible.packages(\"$1\", lib=\"$R_LIBS_USER\")"
}

for p_ in "${packages[@]}"; do

  if [[ "$p_" == *":"* ]] ; then 
    from_github=1
    fp=$(echo $p_|cut -d: -f1)
    commit=$(echo $p_|cut -d: -f2)
    case $fp in
      *"dgpsi-R"*) p=dgpsi ;;
      *"tinydancer"*) p=tinydancer;;
    esac
  else
    from_github=0
    p=$p_
  fi

  if [[ -d $R_LIBS_USER/$p ]]; then
    echo "Found <$p> in $R_LIBS_USER"
  else
    if [ $from_github -eq 1 ] ; then 
      install_package_from_github "$fp" "$commit"
    else
    # Attempt install through standard CRAN
    install_package "$p"
    # If failed: attemps through auto-resolution, or through archive through fixed version
    if [[ ! -d $R_LIBS_USER/$p ]] ; then
      # Attempt auto-resolution
      echo "CRAN install failed, starting auto-resol"
      if [[ ! -d $R_LIBS_USER/oldr ]] ; then
        install_package_from_archive "https://github.com/duckmayr/oldr/archive/26205c4fbb3edf6495bd71f933d04a0a8e9dfea1.tar.gz"
      fi
      install_package_compat $p
      if [[ ! -d $R_LIBS_USER/$p ]] ; then
        echo "Auto-resol failed, starting manual install from hardcoded archive version"
        case $p in
          HI) version="0.5" ;;
          MfUSampler) version="1.0.6" ;;
          MASS) version="7.3-58.3" ;;
          Matrix) version="1.5-0" ;;
          loo) version="2.2.0" ;;
          GenSA) version="1.1.14.1" ;;
          *) echo "STOP: no version hardcoded for <$p>, edit $0."; exit 1;
        esac
        install_package_from_archive "https://cran.r-project.org/src/contrib/Archive/$p/${p}_$version.tar.gz"
      fi
    fi
    fi
    if [[ -d $R_LIBS_USER/$p ]] ; then
      echo "<$p> successfully installed"
    else
      echo "STOP: Problem encountered when installing R package <$p>"; exit 1
    fi
  fi
done

echo "$0: Installed all requested R packages"
