#!/bin/bash
set -euo pipefail

# Create a temporary directory that will be cleaned up on script exit (success or error)
TRASH_DIR=$(mktemp -d)
trap 'rm -rf "$TRASH_DIR"' EXIT

# Find and move all node_modules directories
# -prune prevents descending into node_modules directories
find . -name "node_modules" -type d -prune -print0 | while IFS= read -r -d '' dir; do
  # Generate unique name from path: './frontend/node_modules' -> 'frontend_node_modules'
  unique_name=$(printf '%s\n' "${dir#./}" | tr '/' '_')

  if ! mv -- "$dir" "$TRASH_DIR/$unique_name"; then
    echo "Warning: Failed to move '$dir'. Check permissions." >&2
  fi
done

# Detach the final slow deletion from the script's execution
if [ -n "$(ls -A "$TRASH_DIR")" ]; then
  # Disown the trap and start a new background process for deletion
  trap - EXIT
  nohup rm -rf "$TRASH_DIR" >/dev/null 2>&1 &
fi
