#!/bin/bash
# needswhat.sh - report what a binary or package requires (forward dependencies).
#
# Usage:
#   ./needswhat <package_or_binary>
#   ./needswhat /path/to/root <package_or_binary>

# 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="/"
TARGET=""

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

if [ -z "$TARGET" ]; then
    echo -e "${C_RED}${C_BOLD}Error:${C_RESET} No target specified."
    echo -e "Usage: $0 [ /path/to/root ] <package_or_binary>"
    exit 1
fi

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

declare -A OWNER
declare -A OWNER_BASENAME
declare -A LIB_PATH_64
declare -A LIB_PATH_32
declare -A SEEN_BINS

if ! command -v readelf >/dev/null 2>&1; then
  echo -e "${C_RED}${C_BOLD}Error:${C_RESET} readelf (binutils) not found." >&2
  exit 2
fi

echo -e "${C_BOLD}${C_CYAN}====================================================${C_RESET}"
echo -e "${C_BOLD}${C_CYAN}  Forward Dependency Finder: ${C_YELLOW}${TARGET}${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 ----
echo -ne "${C_BOLD}[1] Indexing package database...${C_RESET} "
pkglog="$ROOT/var/log/packages"
if [ -d "$pkglog" ]; then
    for pkglist in "$pkglog"/*; do
        [ -f "$pkglist" ] || continue
        # Native bash dirname instead of spawning basename
        pkg="${pkglist##*/}"
        while IFS= read -r p; do
            [ -z "$p" ] && continue
            [[ "$p" == */ ]] && continue
            p="${p#./}"
            [[ "$p" != /* ]] && p="/$p"
            
            OWNER["$p"]="$pkg"
            
            # Native bash basename (strips everything up to the last slash)
            bname="${p##*/}"
            if [ -z "${OWNER_BASENAME[$bname]:-}" ] || [[ "$p" != *"/incoming/"* ]]; then
                OWNER_BASENAME["$bname"]="$pkg"
            fi
        done < <(grep -v '^$' "$pkglist" 2>/dev/null)
    done
    echo -e "${C_GREEN}Done.${C_RESET}"
else
    echo -e "${C_YELLOW}Not found.${C_RESET}"
fi

# ---- Index ldconfig cache ----
echo -ne "${C_BOLD}[2] Indexing shared library cache...${C_RESET} "
if [ "$ROOT" = "/" ]; then
    while read -r line; do
        case $line in
            *'=>'*)
                soname=$(echo "$line" | awk '{print $1}')
                path=$(echo "$line" | awk '{print $NF}')
                if [[ "$path" == *"/lib64/"* || "$path" == *"/usr/lib64/"* ]]; then
                    LIB_PATH_64["$soname"]="$path"
                else
                    LIB_PATH_32["$soname"]="$path"
                fi
                ;;
        esac
    done < <(ldconfig -p 2>/dev/null)
    echo -e "${C_GREEN}Done.${C_RESET}"
else
    echo -e "${C_YELLOW}Skipped (alternate root).${C_RESET}"
fi

# --- Helper: Find package owner of a library path ---
find_owner() {
    local path="$1"
    local resolved rel_resolved alt_path
    local bname
    
    [ -z "$path" ] && return
    
    # 1. Exact match
    if [ -n "${OWNER[$path]:-}" ]; then
        echo "${OWNER[$path]}"
        return
    fi
    
    # 2. Try usr-merge variations (e.g., /lib64 vs /usr/lib64)
    if [[ "$path" == /usr/* ]]; then
        alt_path="${path#/usr}"
        if [ -n "${OWNER[$alt_path]:-}" ]; then
            echo "${OWNER[$alt_path]}"
            return
        fi
    elif [[ "$path" != /usr/* ]]; then
        alt_path="/usr${path}"
        if [ -n "${OWNER[$alt_path]:-}" ]; then
            echo "${OWNER[$alt_path]}"
            return
        fi
    fi

    # 3. Resolve symlinks and try again
    if [ -e "$ROOT$path" ]; then
        resolved=$(readlink -f "$ROOT$path")
        
        # Handle ROOT="/" double slash bug
        if [ "$ROOT" = "/" ]; then
            rel_resolved="$resolved"
        else
            rel_resolved="/${resolved#$ROOT/}"
        fi
        
        if [ -n "${OWNER[$rel_resolved]:-}" ]; then
            echo "${OWNER[$rel_resolved]}"
            return
        fi
        
        # Check usr-merge variation for resolved path
        if [[ "$rel_resolved" == /usr/* ]]; then
            alt_path="${rel_resolved#/usr}"
            if [ -n "${OWNER[$alt_path]:-}" ]; then
                echo "${OWNER[$alt_path]}"
                return
            fi
        elif [[ "$rel_resolved" != /usr/* ]]; then
            alt_path="/usr${rel_resolved}"
            if [ -n "${OWNER[$alt_path]:-}" ]; then
                echo "${OWNER[$alt_path]}"
                return
            fi
        fi
    fi

    # 4. Fallback by basename (handles Slackware's /lib64/incoming/ quirk)
    bname=$(basename "$path")
    if [ -n "${OWNER_BASENAME[$bname]:-}" ]; then
        echo "${OWNER_BASENAME[$bname]}"
        return
    fi
}

# ---- Resolve Target to Binaries ----
binaries=()
if [ -f "$ROOT$TARGET" ] || [ -f "$TARGET" ]; then
    if [ -f "$ROOT$TARGET" ]; then
        binaries+=("$ROOT$TARGET")
    else
        binaries+=("$TARGET")
    fi
else
    echo -ne "${C_BOLD}[3] Searching package database for ${TARGET}...${C_RESET} "
    
    pkgfile=$(ls "$pkglog/${TARGET}"* 2>/dev/null | head -n1)
    if [ -z "$pkgfile" ]; then
        pkgfile=$(ls "$pkglog/"*"${TARGET}"* 2>/dev/null | head -n1)
    fi

    if [ -z "$pkgfile" ]; then
        echo -e "${C_RED}Failed.${C_RESET}"
        echo -e "${C_RED}Error: Could not find binary or package '${TARGET}'.${C_RESET}"
        exit 1
    fi
    
    realpkg="${pkgfile##*/}"
    echo -e "${C_GREEN}Found: ${C_CYAN}${realpkg}${C_RESET}"
    
    # Extract both binaries AND shared libraries
    while IFS= read -r p; do
        [ -z "$p" ] && continue
        p="${p#./}"
        [[ "$p" != /* ]] && p="/$p"
        
        if [[ "$p" == /usr/bin/* || "$p" == /usr/sbin/* || "$p" == /bin/* || "$p" == /sbin/* || "$p" == /usr/libexec/* ]]; then
            binaries+=("$ROOT$p")
        elif [[ "$p" == */lib*/* && ( "$p" == *.so || "$p" == *.so.* ) ]]; then
            binaries+=("$ROOT$p")
        fi
    done < <(grep -v '^$' "$pkgfile" 2>/dev/null)
    
    if [ ${#binaries[@]} -eq 0 ]; then
        echo -e "\n${C_YELLOW}Package '${realpkg}' contains no executable binaries or shared libraries to analyze.${C_RESET}"
        echo -e "${C_DIM}It may be a data or configuration package.${C_RESET}"
        exit 0
    fi
fi

# ---- Scan Binaries ----
echo -e "\n${C_BOLD}${C_GREEN}=== Dependencies for ${TARGET} ===${C_RESET}"
elf_count=0

for bin in "${binaries[@]}"; do
    [ -f "$bin" ] || continue
    
    magic=""
    IFS= read -r -N 4 magic 2>/dev/null < "$bin"
    [ "$magic" = $'\x7fELF' ] || continue
    
    # Determine 32-bit or 64-bit
    bin_class=$(readelf -h "$bin" 2>/dev/null | grep 'Class:' | awk '{print $2}')
    [ -z "$bin_class" ] && bin_class="ELF64"

    rel_bin="/${bin#$ROOT/}"
    [ -n "${SEEN_BINS[$rel_bin]:-}" ] && continue
    SEEN_BINS["$rel_bin"]=1
    
    elf_count=$((elf_count + 1))
    bin_pkg="${OWNER[$rel_bin]:-<unowned>}"
    echo -e "\n${C_BOLD}${C_CYAN}▶ ${rel_bin}${C_RESET} ${C_DIM}(from ${bin_pkg}, ${bin_class})${C_RESET}"
    
    needed_list=$(readelf -d "$bin" 2>/dev/null | grep '(NEEDED)' | sed 's/.*\[\(.*\)\]/\1/')
    
    if [ -z "$needed_list" ]; then
        echo -e "  ${C_DIM}(No shared library dependencies)${C_RESET}"
        continue
    fi
    
    while IFS= read -r soname; do
        [ -z "$soname" ] && continue
        
        libpath=""
        
        if [[ "$bin_class" == "ELF64" && -n "${LIB_PATH_64[$soname]:-}" ]]; then
            libpath="${LIB_PATH_64[$soname]}"
        elif [[ "$bin_class" == "ELF32" && -n "${LIB_PATH_32[$soname]:-}" ]]; then
            libpath="${LIB_PATH_32[$soname]}"
        fi
        
        if [ -z "$libpath" ]; then
            if [[ "$bin_class" == "ELF64" ]]; then
                search_dirs=("lib64" "usr/lib64" "lib" "usr/lib")
            else
                search_dirs=("lib" "usr/lib" "lib64" "usr/lib64")
            fi
            for d in "${search_dirs[@]}"; do
                if [ -e "$ROOT/$d/$soname" ]; then
                    libpath="/$d/$soname"
                    break
                fi
            done
        fi
        
        lib_pkg=$(find_owner "$libpath")
        
        if [ -n "$lib_pkg" ]; then
            echo -e "  ${C_DIM}├──${C_RESET} ${C_YELLOW}${soname}${C_RESET} -> ${C_CYAN}${lib_pkg}${C_RESET}"
        elif [ -n "$libpath" ]; then
            echo -e "  ${C_DIM}├──${C_RESET} ${C_YELLOW}${soname}${C_RESET} ${C_DIM}(Locally installed)${C_RESET}"
        else
            echo -e "  ${C_DIM}├──${C_RESET} ${C_YELLOW}${soname}${C_RESET} ${C_RED}(Not found)${C_RESET}"
        fi
    done <<< "$needed_list"
done

if [ "$elf_count" -eq 0 ]; then
    echo -e "  ${C_DIM}No ELF binaries or shared libraries found to analyze.${C_RESET}"
fi