#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

# Define a base directory, assuming this script runs from the project root
BASE_DIR=$(pwd)

# Function to remove directories, with an option to search subdirectories
remove_dirs() {
    local dir=$1
    local search_subdirs=${2:-false}
    echo "Removing path: $dir"
    if [[ "$search_subdirs" == true ]]; then
        find "$BASE_DIR" -name "$dir" -type d -prune -exec rm -rf '{}' +
    else
        rm -rf "$dir" || {
            echo "Failed to remove $dir" >&2
            exit 1
        }
    fi
}

# List of specific directories to remove
declare -a specific_dirs=(
    ".nx"
    ".vscode"
    "node_modules"
    "packages/engine/scram-node/lib"
    "tmp"
)

# Remove specific directories safely
for dir in "${specific_dirs[@]}"; do
    remove_dirs "$BASE_DIR/$dir"
done

# List of directories to search and remove
declare -a subdirs=(
    "dist"
    "build"
    "cmake-build-*"
    "coverage"
    "node_modules"
)


# Remove directories found in subdirectories
for dir in "${subdirs[@]}"; do
    remove_dirs "$dir" true
done

remove_dirs "$(pnpm store path)"

echo "Cleanup completed successfully."
