#!/usr/bin/env bash
# Cloud Agent update script (runs at repo root after git pull).
# Idempotent: reinstall Quarto only if missing; then quarto check; optional renv restore.

set -euo pipefail

if ! quarto --version >/dev/null 2>&1; then
  echo "Quarto not found; installing v1.9.37..."
  curl -fsSL -o /tmp/quarto.deb \
    "https://github.com/quarto-dev/quarto-cli/releases/download/v1.9.37/quarto-1.9.37-linux-amd64.deb"
  sudo dpkg -i /tmp/quarto.deb
  rm -f /tmp/quarto.deb
fi

quarto check

if command -v Rscript >/dev/null 2>&1; then
  Rscript -e "
if (file.exists('renv.lock')) {
  if (!requireNamespace('renv', quietly = TRUE)) {
    install.packages('renv', repos = 'https://cloud.r-project.org')
  }
  renv::restore(prompt = FALSE)
} else {
  message('No root renv.lock; using snapshot R packages')
}
"
else
  echo "WARN: Rscript not found; skip renv::restore. Re-save Cloud Snapshot with R >= 4.2 or install r-base."
fi

echo "Cloud update script complete."
