#!/bin/bash
# depcheck -- report ELF binaries with unresolved shared libraries.

# 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"

scanned=0
had_missing=0
spin_idx=0
spin_chars=('|' '/' '-' '\')

declare -A LD_CACHE
declare -A SEEN_DIR
declare -A PKG_OWNER

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

echo -e "${C_BOLD}${C_CYAN}====================================================${C_RESET}"
echo -e "${C_BOLD}${C_CYAN}       ELF Binary Dependency Auditor (depcheck)     ${C_RESET}"
echo -e "${C_BOLD}${C_CYAN}====================================================${C_RESET}\n"

# 1. Map sonames known to the loader cache
while read -r name _path; do
  [ -n "$name" ] && LD_CACHE["$name"]=1
done < <(ldconfig -p 2>/dev/null | awk '/=>/{print $1}')

# 2. Build an index of File Path -> Package Name using /var/log/packages
echo -ne "${C_BOLD}Indexing package database...${C_RESET} "
for pkgfile in /var/log/packages/*; do
  [ -f "$pkgfile" ] || continue
  pkg_name=$(basename "$pkgfile")
  pkg_name="${pkg_name%%-[0-9]*}" # Strip version/arch/build
  
  while IFS= read -r p; do
    p="${p#./}"
    p="${p#/}"
    if [ -n "$p" ]; then
      PKG_OWNER["/$p"]="$pkg_name"
    fi
  done < <(grep -v '^$' "$pkgfile" 2>/dev/null)
done
echo -e "${C_GREEN}Done.${C_RESET}"

# Helper to look up the package owner of a given path
get_pkg_owner() {
  local file="$1"
  local owner="${PKG_OWNER[$file]:-}"
  
  # Fallback for usr-merge (/lib vs /usr/lib) if the exact path isn't found
  if [ -z "$owner" ]; then
    if [[ "$file" == /usr/* ]]; then
      owner="${PKG_OWNER[${file#/usr}]:-}"
    else
      owner="${PKG_OWNER[/usr$file]:-}"
    fi
  fi
  
  if [ -n "$owner" ]; then
    echo -e "${C_DIM}(package: ${owner})${C_RESET}"
  else
    echo -e "${C_DIM}(unowned)${C_RESET}"
  fi
}

# Echo one "    <lib> not found" line per unresolved NEEDED entry.
resolve_missing() {
  local f="$1" fdir line lib dir rp
  local needed="" rpraw="" d
  local rpaths=()

  d=$(readelf -d "$f" 2>/dev/null)
  [ -n "$d" ] || return 0

  while IFS= read -r line; do
    case $line in
      *'(NEEDED)'*)
        lib=${line##*[}; needed+="${lib%]}"$'\n';;
      *'(RUNPATH)'*|*'(RPATH)'*)
        rp=${line##*[}; rpraw+="${rp%]}:";;
    esac
  done <<< "$d"
  [ -n "$needed" ] || return 0

  fdir=$(dirname "$f")
  if [ -n "$rpraw" ]; then
    IFS=':' read -ra rpaths <<< "$rpraw"
  fi

  while IFS= read -r lib; do
    [ -n "$lib" ] || continue
    [ -n "${LD_CACHE[$lib]:-}" ] && continue
    local found=0
    local extra_dirs=("$fdir")
    if [ -d "$fdir" ]; then
      for sub in "$fdir"/*/; do
        [ -d "$sub" ] && extra_dirs+=("${sub%/}")
      done
    fi

    for dir in "${rpaths[@]}" "${extra_dirs[@]}" /lib /usr/lib /lib64 /usr/lib64; do
      dir=${dir//'${ORIGIN}'/$fdir}
      dir=${dir//'$ORIGIN'/$fdir}
      dir=${dir//'${LIB}'/lib64}
      dir=${dir//'$LIB'/lib64}
      if [ -n "$dir" ] && [ -e "$dir/$lib" ]; then
        found=1
        break
      fi
    done
    [ "$found" -eq 0 ] && echo "    ${lib} not found"
  done <<< "$needed"
}

check_file() {
  local f="$1" missing
  missing=$(resolve_missing "$f")
  if [ -n "$missing" ]; then
    had_missing=1
    # Print the missing file along with its owning package
    echo -e "\n${C_RED}${C_BOLD}❌ $f${C_RESET} $(get_pkg_owner "$f")"
    while read -r line; do
      [ -n "$line" ] && echo -e "   ${C_YELLOW}↳${C_RESET} ${line#    }"
    done <<< "$missing"
  fi
}

scan() {
  local dir="$1" rp f magic
  [ -d "$dir" ] || return
  rp=$(readlink -f "$dir")
  [ -n "${SEEN_DIR[$rp]:-}" ] && return
  SEEN_DIR["$rp"]=1

  while IFS= read -r -d '' f; do
    # Skip symlinked entries
    [ -L "$f" ] && continue

    # \x7fELF magic, read in-shell to avoid spawning a process per file.
    magic=""
    IFS= read -r -N 4 magic 2>/dev/null < "$f"
    [ "$magic" = $'\x7fELF' ] || continue

    scanned=$((scanned + 1))
    
    # Update spinner every 100 files
    if (( scanned % 100 == 0 )); then
      printf "\r${C_DIM}[%s] Scanned: %d | Missing: %d${C_RESET}  " \
        "${spin_chars[$spin_idx]}" "$scanned" "$had_missing" >&2
      spin_idx=$(( (spin_idx + 1) % 4 ))
    fi

    check_file "$f"
  done < <(find -L "$dir" -type f -print0 2>/dev/null)
}

echo -e "\n${C_BOLD}${C_CYAN}[1] Scanning system binaries...${C_RESET}"
scan /usr/bin
scan /usr/sbin
scan /bin
scan /sbin
scan /usr/libexec
scan /usr/lib64
# Clear the spinner line
printf "\r\033[K"

echo -e "${C_BOLD}${C_CYAN}[2] Java runtime check...${C_RESET}"
JAVA_BIN=$(command -v java 2>/dev/null || true)
# Check if any Java package is installed in the Slackware package database
JAVA_PKGS=$(ls /var/log/packages/ 2>/dev/null | grep -iE '^(jdk|jre|openjdk|zulu)' | tr '\n' ' ')

if [ -n "$JAVA_BIN" ]; then
  real_java=$(readlink -f "$JAVA_BIN")
  echo -e "    Found: ${C_DIM}$real_java${C_RESET} $(get_pkg_owner "$real_java")"
  java_missing=$(resolve_missing "$real_java")
  if [ -n "$java_missing" ]; then
    had_missing=1
    while read -r line; do
      [ -n "$line" ] && echo -e "   ${C_YELLOW}↳${C_RESET} ${line#    }"
    done <<< "$java_missing"
  else
    echo -e "    ${C_GREEN}✅ (no unresolved libraries)${C_RESET}"
  fi
else
  if [ -n "$JAVA_PKGS" ]; then
    # Java package exists, but binary is not in PATH
    echo -e "    ${C_YELLOW}⚠️  Java package installed, but 'java' not in PATH.${C_RESET}"
    echo -e "    ${C_DIM}Packages: $JAVA_PKGS${C_RESET}"
  else
    # Java isn't installed at all, so we just quietly note it and move on
    echo -e "    ${C_DIM}Java is not installed (or no package detected).${C_RESET}"
  fi
fi

echo -e "\n${C_BOLD}${C_CYAN}[3] Package database sanity...${C_RESET}"
echo -e "    Installed packages: ${C_BOLD}$(find /var/log/packages/ -maxdepth 1 -type f 2>/dev/null | wc -l)${C_RESET}"
echo -e "    ldconfig entries:   ${C_BOLD}$(ldconfig -p 2>/dev/null | wc -l)${C_RESET}"

echo -e "\n${C_BOLD}${C_CYAN}[4] Boot-time complaints (last kernel messages)...${C_RESET}"
if dmesg 2>/dev/null | grep -iE 'not found|no such file|cannot open' | head -5 | grep -q .; then
  dmesg 2>/dev/null | grep -iE 'not found|no such file|cannot open' | head -5 | sed 's/^/    /'
else
  echo -e "    ${C_GREEN}✅ No missing file errors in dmesg.${C_RESET}"
fi

echo -e "\n${C_BOLD}${C_CYAN}====================================================${C_RESET}"
if [ "$had_missing" -eq 0 ] && [ "$scanned" -gt 0 ]; then
  echo -e "${C_GREEN}${C_BOLD}✅ OK:${C_RESET} Scanned $scanned ELF file(s); no unresolved shared libraries."
elif [ "$scanned" -eq 0 ]; then
  echo -e "${C_YELLOW}${C_BOLD}⚠️  WARNING:${C_RESET} No ELF files found."
else
  echo -e "${C_RED}${C_BOLD}❌ FAILED:${C_RESET} Found unresolved libraries (scanned $scanned ELF file(s))."
fi
echo -e "${C_BOLD}${C_CYAN}====================================================${C_RESET}"

[ "$had_missing" -eq 1 ] && exit 1
exit 0