#!/bin/bash
# whoneeds - report what links a given library on this system.
#
# Usage:
#   whoneeds <library_name>
#   whoneeds /path/to/root <library_name>

# Colors
C_RESET="\e[0m"
C_GREEN="\e[32m"
C_RED="\e[31m"
C_YELLOW="\e[33m"
C_CYAN="\e[36m"
C_BOLD="\e[1m"
C_DIM="\e[2m"

ROOT="/"
LIB=""

for arg in "$@"; do
    case "$arg" in
        /*) [ -d "$arg" ] && ROOT="$arg" ;;
        *)  LIB="$arg" ;;
    esac
done

if [ -z "$LIB" ]; then
    echo -e "${C_RED}${C_BOLD}Error:${C_RESET} No library or package name specified."
    echo -e "Usage: $0 [ /path/to/root ] <library_name>"
    exit 1
fi

[ "$ROOT" != "/" ] && ROOT="${ROOT%/}"

declare -A OWNER
declare -A HITS
scanned=0
spin_idx=0
spin_chars=('|' '/' '-' '\')

# --- Normalize Library Names ---
# If user types "libpng", LIB_NAME="png", SEARCH_LIB="libpng"
# If user types "gpm", LIB_NAME="gpm", SEARCH_LIB="libgpm"
LIB_NAME="${LIB#lib}"
SEARCH_LIB="lib${LIB_NAME}"

# Regex explanation:
# \[libpng      - Matches the start of the SONAME
# [-0-9.]*      - Matches version numbers (e.g., 16 in libpng16, or -1.6)
# \.so          - Matches the literal .so
# This matches [libpng16.so and [libgpm.so, but NOT [libpangocairo.so
SONAME_RE="\[${SEARCH_LIB}[-0-9.]*\.so"

echo -e "${C_BOLD}${C_CYAN}====================================================${C_RESET}"
echo -e "${C_BOLD}${C_CYAN}  Reverse Dependency Finder: ${C_YELLOW}${LIB}${C_CYAN}   ${C_RESET}"
echo -e "${C_BOLD}${C_CYAN}  Root: ${C_DIM}${ROOT}${C_RESET}"
echo -e "${C_BOLD}${C_CYAN}====================================================\n${C_RESET}"

# ---- Index /var/log/packages ----
pkglog="$ROOT/var/log/packages"
if [ -d "$pkglog" ]; then
    echo -ne "${C_BOLD}[1] Indexing package database...${C_RESET} "
    for pkglist in "$pkglog"/*; do
        [ -f "$pkglist" ] || continue
        pkg=$(basename "$pkglist")
        while IFS= read -r p; do
            # Skip empty lines and directories
            [ -z "$p" ] && continue
            [[ "$p" == */ ]] && continue
            
            # Normalize path: remove ./ and ensure leading /
            p="${p#./}"
            [[ "$p" != /* ]] && p="/$p"
            
            OWNER["$p"]="$pkg"
        done < <(grep -v '^$' "$pkglist" 2>/dev/null)
    done
    echo -e "${C_GREEN}Done.${C_RESET}"
else
    echo -e "${C_YELLOW}[1] No package database found at $pkglog.${C_RESET}"
fi

# ---- Resolve which sonames and .pc files the target actually ships ----
# Derive both from the package database instead of guessing from the
# user's argument. Handles cases where the package name and the file
# stem differ (libnl3 -> libnl-3.so.200 + libnl-3.0.pc,
# libgdk-pixbuf -> libgdk_pixbuf-2.0.so.0, libjpeg-turbo -> libjpeg.so.8).
# Also accepts the case where the user typed a stem instead of a package
# name (e.g. "libnl-3").
declare -A TARGET_SONAMES=()
declare -A TARGET_PC=()

for path in "${!OWNER[@]}"; do
    base="${path##*/}"
    pkg="${OWNER[$path]}"

    pkg_match=0
    if [[ "$pkg" == "$LIB"        || "$pkg" == "${LIB}-"*        || \
          "$pkg" == "$SEARCH_LIB" || "$pkg" == "${SEARCH_LIB}-"* ]]; then
        pkg_match=1
    fi

    case "$base" in
        *.so|*.so.*)
            if [ "$pkg_match" -eq 1 ]; then
                TARGET_SONAMES["$base"]=1
            else
                case "$base" in
                    "${SEARCH_LIB}".so|"${SEARCH_LIB}".so.*|\
                    "${SEARCH_LIB}"[-._]*.so|"${SEARCH_LIB}"[-._]*.so.*)
                        TARGET_SONAMES["$base"]=1 ;;
                esac
            fi
            ;;
        *.pc)
            if [ "$pkg_match" -eq 1 ]; then
                TARGET_PC["$base"]=1
            else
                case "$base" in
                    "${LIB}".pc|"${SEARCH_LIB}".pc|\
                    "${LIB}"[-._]*.pc|"${SEARCH_LIB}"[-._]*.pc)
                        TARGET_PC["$base"]=1 ;;
                esac
            fi
            ;;
    esac
done

if [ ${#TARGET_SONAMES[@]} -gt 0 ]; then
    echo -e "${C_DIM}    Resolved sonames: ${!TARGET_SONAMES[*]}${C_RESET}"
else
    echo -e "${C_YELLOW}    Note: no matching sonames found in ${pkglog};${C_RESET}"
    echo -e "${C_YELLOW}    falling back to prefix guess (may miss hyphenated stems).${C_RESET}"
fi

# ---- Candidate dirs ----
dirs=()
for d in usr/bin usr/sbin usr/libexec bin sbin \
         usr/lib64 usr/lib lib64 lib usr/local/bin usr/local/lib64; do
    [ -d "$ROOT/$d" ] && dirs+=("$ROOT/$d")
done
[ ${#dirs[@]} -gt 0 ] || { echo -e "${C_RED}Error: No binary dirs under $ROOT${C_RESET}" >&2; exit 1; }

# ---- Scan ----
echo -e "${C_BOLD}[2] Scanning binaries for links to ${C_YELLOW}${LIB}${C_BOLD}...${C_RESET}"
while IFS= read -r -d '' f; do
    magic=""
    IFS= read -r -N 4 magic 2>/dev/null < "$f"
    [ "$magic" = $'\x7fELF' ] || continue
    
    ((scanned++))
    
    if (( scanned % 200 == 0 )); then
        printf "\r${C_DIM}[%s] Scanned: %d files...${C_RESET}  " \
            "${spin_chars[$spin_idx]}" "$scanned" >&2
        spin_idx=$(( (spin_idx + 1) % 4 ))
    fi

    # Match against the sonames the target package actually provides.
    # Fall back to the prefix regex only when the package DB gave us
    # nothing (e.g. unowned libraries on a live system).
    dyn=$(readelf -dW "$f" 2>/dev/null) || continue
    hit=0
    while IFS= read -r need; do
        [ -z "$need" ] && continue
        if [ ${#TARGET_SONAMES[@]} -gt 0 ]; then
            [ -n "${TARGET_SONAMES[$need]:-}" ] && { hit=1; break; }
        else
            [[ "$need" =~ ^${SEARCH_LIB}[-0-9.]*\.so ]] && { hit=1; break; }
        fi
    done < <(awk '/NEEDED/ { sub(/.*\[/, ""); sub(/\].*/, ""); print }' <<< "$dyn")
    [ "$hit" -eq 1 ] || continue
    
    
    rel="/${f#$ROOT/}"
    pkg="${OWNER[$rel]:-<unowned>}"
    HITS["$pkg"]+="  ${C_DIM}↳${C_RESET} $rel"$'\n'
done < <(find "${dirs[@]}" -type f -print0 2>/dev/null)

# Clear the spinner line
printf "\r\033[K"

# ---- Report ----
if [ ${#HITS[@]} -eq 0 ]; then
    echo -e "\n${C_YELLOW}Nothing under ${ROOT} links against ${C_BOLD}${SEARCH_LIB}${C_RESET}"
    exit 0
fi

echo -e "\n${C_BOLD}${C_GREEN}=== Packages that will break if you remove ${LIB} ===${C_RESET}"
for pkg in $(printf '%s\n' "${!HITS[@]}" | sort); do
    if [ "$pkg" = "<unowned>" ]; then
        echo -e "\n${C_YELLOW}>>> Locally installed files${C_RESET}"
    else
        # Check if this package is the one providing the library.
        # Handles both "gpm" and "libpng" naming styles.
        if [[ "$pkg" == "${LIB}"* ]] || [[ "$pkg" == "${SEARCH_LIB}"* ]]; then
            echo -e "\n${C_BOLD}${C_RED}>>> ${pkg} ${C_DIM}(This is the package you are checking)${C_RESET}"
        else
            echo -e "\n${C_BOLD}${C_CYAN}>>> ${pkg}${C_RESET}"
        fi
    fi
    printf "%b" "${HITS[$pkg]}"
done

# ---- Build-time signal ----
echo -e "\n${C_BOLD}${C_GREEN}=== Build-time indicators (.pc files) ===${C_RESET}"
found=0
if [ ${#TARGET_PC[@]} -gt 0 ]; then
    for pcdir in "$ROOT/usr/lib64/pkgconfig" "$ROOT/usr/lib/pkgconfig" \
                 "$ROOT/usr/share/pkgconfig"; do
        [ -d "$pcdir" ] || continue
        for pc_name in "${!TARGET_PC[@]}"; do
            pc="$pcdir/$pc_name"
            [ -f "$pc" ] || continue
            rel="/${pc#$ROOT/}"
            pkg="${OWNER[$rel]:-<unowned>}"
            if [ "$pkg" = "<unowned>" ]; then
                printf "  ${C_DIM}%s${C_RESET}  ${C_RED}(untracked)${C_RESET}\n" "$rel"
            else
                printf "  ${C_DIM}%s${C_RESET}  ${C_CYAN}(%s)${C_RESET}\n" "$rel" "$pkg"
            fi
            found=1
        done
    done
fi
[ "$found" -eq 1 ] || echo -e "  ${C_DIM}(none found)${C_RESET}"
