#!/bin/bash

LIBDIR="${1:-/mnt/us/python3/usr/lib}"  # Default lib path
SCANROOT="${2:-/mnt/us/python3}"        # Default scan path
MODE="${3:-report}"                     # Can be 'report' or 'prune'

echo "📦 Scanning for used libraries in: $SCANROOT"
echo "🔍 Comparing against: $LIBDIR"
echo "⚙️  Mode: $MODE"

USED_LIBS=$(mktemp)
ALL_LIBS=$(mktemp)

# Step 1: Find all .so, ELF binaries, and extract NEEDED entries
find "$SCANROOT" -type f -exec readelf -d {} \; 2>/dev/null |
  grep 'NEEDED' | awk -F'[][]' '{ print $2 }' | sort -u > "$USED_LIBS"

# Step 2: Get actual .so* files in libdir
find "$LIBDIR" -maxdepth 1 -type f -name 'lib*.so*' -exec basename {} \; | sort -u > "$ALL_LIBS"

echo "🔎 Libraries actually referenced (NEEDED):"
cat "$USED_LIBS"

echo ""
echo "📁 All libraries present in $LIBDIR:"
cat "$ALL_LIBS"

echo ""
echo "❓ Unused libraries in $LIBDIR:"
comm -23 "$ALL_LIBS" "$USED_LIBS"

# Step 3: Optionally prune
if [[ "$MODE" == "prune" ]]; then
  echo ""
  echo "⚠️ Pruning unused libraries from $LIBDIR..."
  comm -23 "$ALL_LIBS" "$USED_LIBS" | while read -r lib; do
    echo "🗑️  Deleting: $lib"
    rm -f "$LIBDIR/$lib"
  done
fi

# Cleanup
rm -f "$USED_LIBS" "$ALL_LIBS"
