#!/usr/bin/env bash
set -euo pipefail

# Wiki update script - runs as student user
# This script clones or updates the wiki repository

REPO_URL="${WIKI_REPO_URL:-https://git.zuccaro.me/bzuccaro/LLM-Labs.git}"
WIKI_DIR="${HOME}/wiki"
STUDENT_USER="${SUDO_USER:-student}"

run_as_student() {
  sudo -u "$STUDENT_USER" -- "$@"
}

if [ -d "$WIKI_DIR/.git" ]; then
  echo "Updating existing wiki..."
  run_as_student git -C "$WIKI_DIR" pull --ff-only
else
  echo "Cloning wiki repository..."
  tmp_dir=$(mktemp /tmp/wiki.clone.XXXXXX)
  chown "$STUDENT_USER:$STUDENT_USER" "$tmp_dir"
  rmdir "$tmp_dir"
  
  run_as_student git clone "$REPO_URL" "$tmp_dir"
  
  # Preserve node_modules and .next if they exist
  if [ -d "$WIKI_DIR/node_modules" ] && [ ! -e "$tmp_dir/node_modules" ]; then
    mv "$WIKI_DIR/node_modules" "$tmp_dir/node_modules"
  fi
  
  if [ -d "$WIKI_DIR/.next" ] && [ ! -e "$tmp_dir/.next" ]; then
    mv "$WIKI_DIR/.next" "$tmp_dir/.next"
  fi
  
  rm -rf "$WIKI_DIR"
  mv "$tmp_dir" "$WIKI_DIR"
  chown -R "$STUDENT_USER:$STUDENT_USER" "$WIKI_DIR"
fi

# Install dependencies if needed
if [ ! -d "$WIKI_DIR/node_modules" ]; then
  echo "Installing wiki dependencies..."
  run_as_student bash -lc "cd '$WIKI_DIR' && npm install --no-fund --no-audit"
fi

echo "Wiki updated successfully!"
