#!/bin/bash

# Name of the conda environment to create
CONDA_ENV_NAME="shiny_server_CDL"

# Create a conda environment with R essentials
conda create --name $CONDA_ENV_NAME r-essentials -y

# Activate the conda environment
conda activate $CONDA_ENV_NAME

# Run an R script to list the user's installed R packages
Rscript -e 'writeLines(row.names(installed.packages(lib.loc = .libPaths()[1])))' > user_packages.txt

# Read the list of packages and install them in the conda environment
while read package; do
    # Attempt to install from conda
    conda install -n $CONDA_ENV_NAME --yes "r-$package" || {
        # If not available in conda, install from CRAN using R
        Rscript -e "install.packages('$package')"
    }
done < user_packages.txt

# Deactivate the conda environment
conda deactivate

# Clean up
rm user_packages.txt
