#!/bin/bash
#
# depfinder - a script that finds slackware package dependencies.
#
# Written by George Vlahavas 
# (vlahavas~at~gmail~dot~com)
#
# Licensed under the GPL v3

VERSION=2.0

CWD=`pwd`

# Set default settings
CREATEDEPFILE=0
CHECKALLFILES=0
VERSIONINFO=0
PYTHONDEPS=0
JOBS=1
STARTDIR=""
# DEPFINDERDEBUG=1 keeps the working directory, for inspection
DFDEBUG=${DEPFINDERDEBUG:-0}
DEPFINDERSEARCH="/usr/libexec/depfinder-search"
DEPFINDERPYTHON="/usr/libexec/depfinder-python"
LIBDIRSUFFIX=""
# The installed package database. Can be overridden for testing.
PKGDB=${DEPFINDERPKGDB:-/var/lib/pkgtools/packages}

# help message
help_msg()
{
echo \
"depfinder: finds the dependencies of Slackware packages

usage: depfinder [OPTIONS] <package.tgz|.txz|.tlz|.tbz|.tbr or packaging-dir>

OPTIONS:
    -f,          Output dependencies to a file instead of stdout.
                 By default it creates a .dep file. See also -s.
    -s,          Outputs dependencies with version information. If
                 combined with -f, it creates a slack-required file
    -a,          Checks all files in the directory tree instead of
                 following the FHS
    -p,          Attempts to detect python dependencies.
    -j <jobs>,   The number of parallel depfinder jobs to run. Can help
                 with large packages; best set to the number of your
                 CPUs/cores (default: 1)
    -v,          Show version information
    -h,          This help message"
}

# version message
ver_msg()
{
echo \
"depfinder version $VERSION (c) 2009-2026 George Vlahavas
Run \"depfinder -h\" for help information"
}

# Routine to find out which packages each library (or python module) in
# a part of the list comes from. depfinder-search reads the package
# database once for the whole list and prints a line per library, with
# the packages providing it separated by "|" ("either of"), or an empty
# line if no package provides it. Those libraries are listed in
# UNOWNED<part>.
depfind()
{
	if ! "$DEPFINDERSEARCH" "$PKGDB" pkglist.log LIBS$1 > DEPS$1; then
		touch FAILED$1
	fi
	awk 'FILENAME == ARGV[1] { lib[FNR] = $0; next }
		$0 == "" { print lib[FNR] }' LIBS$1 DEPS$1 > UNOWNED$1
}

# Function that finds python files in the current directory, where the
# current directory is always the packaging directory here. Since
# python scripts could be all over the place, we're looking everywhere
# in the package by default. Besides *.py files, these are scripts whose
# first line is a python #! line. (Reading only the first line is much
# faster than running file on every file in the package.)
findpython()
{
	find ./ -type f ! -name "*.py" -exec awk \
		'FNR == 1 { if ($0 ~ /^#!.*python/) print FILENAME; nextfile }' {} + \
		2> /dev/null
	find ./ \
	-type f -name "*.py"
}

# Function that cleans up temp files
cleanup()
{
	if [ "$DFDEBUG" != 1 ] && [ -n "$DFTMP" ]; then
		rm -rf "$DFTMP"
	fi
}

# Function to clean up when depfinder is killed: stops the jobs running
# in the background, so they don't write into the working directory
# while it is removed, and exits with the status of signal number $1
interrupted()
{
	kill `jobs -p` 2> /dev/null
	wait
	cleanup
	exit $((128 + $1))
}

# Function to cleanly exit on error (just to be sure)
err()
{
	cleanup
	exit 1
}

#
# This is where everything starts...
#


# If no arguments are passed, show an error message
if [ $# -eq 0 ]; then
	help_msg
	echo "ERROR: No arguments found." >&2
	err
fi

# check which switches are used
while getopts  ":hvfsapj:" flag
do
	# if switch is unknown show help and fail
	if [ $flag = "?" ]; then
		help_msg
		echo "ERROR: unknown option -$OPTARG" >&2
		err
	fi
	# an option without its argument (only -j has one)
	if [ $flag = ":" ]; then
		help_msg
		echo "ERROR: -$OPTARG needs a number of jobs" >&2
		err
	fi
	if [ $flag = "h" ]; then
		help_msg
		exit 0
	fi
	if [ $flag = "v" ]; then
		ver_msg
		exit 0
	fi
	if [ $flag = "f" ]; then
		CREATEDEPFILE=1
	fi
	if [ $flag = "s" ]; then
		VERSIONINFO=1
	fi
	if [ $flag = "a" ]; then
		CHECKALLFILES=1
	fi
	if [ $flag = "p" ]; then
		PYTHONDEPS=1
	fi
	if [ $flag = "j" ]; then
		# it must be a number...
		case "$OPTARG" in
			""|*[!0-9]*)
				help_msg
				echo "ERROR: -j needs a number of jobs, not \"$OPTARG\"" >&2
				err
				;;
		esac
		# ... in decimal, even with leading zeros, and at least 1
		JOBS=$((10#$OPTARG))
		if [ $JOBS -lt 1 ]; then
			help_msg
			echo "ERROR: The number of jobs must be at least 1" >&2
			err
		fi
	fi
done

# we shift positions in $@ so that we discard all previous switches
# and leave only files as additional arguments
shift $((OPTIND-1))

# There must be a package left after the options
if [ $# -eq 0 ]; then
	help_msg
	echo "ERROR: No package or packaging directory given" >&2
	err
fi

# Only one package at a time!
if [ $# -gt 1 ]; then
	help_msg
	echo "ERROR: Too many arguments" >&2
	err
fi

# A path starting with "-" would be taken for an option by the tools
# it's passed to
case "$1" in
	-*) set -- "./$1" ;;
esac

# test if the package file is there
if [ ! -d "$1" ] && [ ! -f "$1" ] ; then
	arg=$1
	echo "ERROR: $arg not found" >&2
	err
fi

# test if the files is actually a directory...
if [ -d "$1" ]; then
	STARTDIR=`readlink -f "$1"`/
else
	# ... or has the .tgz|tbz|tlz extension (is a package file)
	if ! echo "$1" | grep -q "\.t[gblx]z$\|\.tbr$"; then
		arg=$1
		echo "ERROR: $arg is not a package file or a directory!" >&2
		err
	fi
fi

# The package database must be there
if [ ! -d "$PKGDB" ]; then
	echo "ERROR: package database $PKGDB not found" >&2
	err
fi

# depfinder-search must be there
if [ ! -x "$DEPFINDERSEARCH" ]; then
	echo "ERROR: $DEPFINDERSEARCH not found" >&2
	err
fi

# -p needs python 3
if [ $PYTHONDEPS -eq 1 ] && ! command -v python3 > /dev/null; then
	echo "ERROR: python3 is needed to detect python dependencies (-p)" >&2
	err
fi
if [ $PYTHONDEPS -eq 1 ] && [ ! -f "$DEPFINDERPYTHON" ]; then
	echo "ERROR: $DEPFINDERPYTHON not found" >&2
	err
fi

# Create the working directory, with a name that can't be guessed. The
# package is extracted into its pkg subdirectory, apart from
# depfinder's own files.
DFTMP=`mktemp -d "${TMPDIR:-/tmp}/depfinder.XXXXXX"`
if [ -z "$DFTMP" ]; then
	echo "ERROR: could not create a temporary directory" >&2
	err
fi
trap "interrupted 1" HUP
trap "interrupted 2" INT
trap "interrupted 15" TERM
[ "$DFDEBUG" != 1 ] || echo "DEBUG: working directory is $DFTMP" >&2
mkdir "$DFTMP/pkg"
ls "$PKGDB" > "$DFTMP/pkglist.log"

# Extract only if argument is not a directory
if [ -z "$STARTDIR" ]; then
	if echo "$1" | grep -q "\.tgz$"; then
		DECOMPRESS="gzip -d -c"
	elif echo "$1" | grep -q "\.tbz$"; then
		DECOMPRESS="bzip2 -d -c"
	elif echo "$1" | grep -q "\.tlz$"; then
		# .tlz packages are lzip compressed. Use plzip if available, like
		# installpkg does, since it decompresses using multiple threads.
		if command -v plzip > /dev/null; then
			DECOMPRESS="plzip -d -c"
		else
			DECOMPRESS="lzip -d -c"
		fi
	elif echo "$1" | grep -q "\.txz$"; then
		DECOMPRESS="xz -d -c"
	elif echo "$1" | grep -q "\.tbr$"; then
		DECOMPRESS="brotli -d -c"
	else
		echo "ERROR: $1 is not a package file or a directory!" >&2
		err
	fi
	$DECOMPRESS "$1" | tar xf - -C "$DFTMP/pkg"
	STATUS=("${PIPESTATUS[@]}")
	if [ ${STATUS[0]} -ne 0 ] || [ ${STATUS[1]} -ne 0 ]; then
		echo "ERROR: could not extract $1" >&2
		err
	fi
fi
# The root of the package's files
PKGROOT=${STARTDIR:-$DFTMP/pkg/}

# (for a directory, from its full path, so that "." is named too)
if [ -z "$STARTDIR" ]; then
	PKGNAME=`basename "$1" | sed "s/\.t[gblx]z$\|\.tbr$//"`
else
	PKGNAME=`basename "$STARTDIR"`
fi

# The name of the package without version, used to exclude the package
# itself from the dependency list. For a package file it comes from the
# file name (name-version-arch-build). For a packaging directory it comes
# from install/slack-desc, if there is one.
if [ -z "$STARTDIR" ]; then
	SELFNAME=`echo "$PKGNAME" | sed "s/-[^-]*-[^-]*-[^-]*$//"`
else
	SELFNAME=`sed -n "s/^\([^ #:]\+\):.*/\1/p" "$STARTDIR/install/slack-desc" \
		2> /dev/null | head -n 1`
fi

# Find all binaries and libs in the package
cd "$PKGROOT"
# (file is run on many files at once; -0 puts a NUL after each name)
if [ $CHECKALLFILES -eq 0 ]; then
	# usually only in standard locations. usr/lib and lib are searched
	# on 64-bit too, since many packages put programs in usr/lib/<name>.
	SEARCHDIRS="sbin usr/sbin usr/bin bin usr/libexec usr/games usr/lib lib"
	if [ -n "$LIBDIRSUFFIX" ]; then
		SEARCHDIRS="$SEARCHDIRS usr/lib${LIBDIRSUFFIX} lib${LIBDIRSUFFIX}"
	fi
else
	# or anywhere in the package if -a is specified
	SEARCHDIRS="./"
fi
LC_ALL=C find $SEARCHDIRS -type f -exec file -N -0 {} + 2> /dev/null | \
awk -F '\0' '$2 ~ /^: ELF / { print $1 }' > "$DFTMP/FILES"

# Look for python dependencies: depfinder-python parses the python
# files for the modules they import (and reads the requirements in the
# package's python metadata), and lists the files on the system that
# provide them. It warns about the ones it can't find.
if [ $PYTHONDEPS -eq 1 ]; then
	findpython > "$DFTMP/PYTHONFILES"
	# (-s: modules installed in the user's home don't count, -E: nor do
	# the ones in PYTHONPATH, e.g. a source tree)
	python3 -s -E "$DEPFINDERPYTHON" "$PKGROOT" "$DFTMP/PYTHONFILES" \
		> "$DFTMP/PYTHONNEEDEDMODULES"
	if [ $? -ne 0 ]; then
		echo "ERROR: could not detect the python dependencies" >&2
		err
	fi
fi

cd "$DFTMP"

# Dump the dependencies to a file. ldd is run on many files at once, in
# $JOBS parallel jobs. File names in FILES are relative to the package
# root.
# There's no point in more jobs than files.
TOTALFILES=`wc -l < FILES`
LDDJOBS=$JOBS
[ $LDDJOBS -gt $TOTALFILES ] && LDDJOBS=$TOTALFILES
[ $LDDJOBS -eq 0 ] && LDDJOBS=1
split -d -a 4 -n l/$LDDJOBS FILES FILES
for i in $( seq -f "%04.f" 0 $(($LDDJOBS-1)) ); do
	# (LD_PRELOAD is unset, or ldd would list the preloaded libraries
	# and their dependencies for every file)
	( cd "$PKGROOT" && \
		LC_ALL=C env -u LD_PRELOAD xargs -r -d '\n' ldd \
		< "$DFTMP/FILES$i" 2> /dev/null ) \
	| grep "=>" \
	| sed "s/\(.*\) => \/\(.*\) \(.*\)/\2/" \
	| sed "s/=> not found/NOT FOUND/" \
	| grep -v "=>" > LIBSM$i &
done
wait
touch LIBSM
cat LIBSM[0-9]* >> LIBSM 2> /dev/null

# linux-gate.so.1 is always a dead-end so we don't look for that at all
LC_ALL=C sort LIBSM | uniq | grep -v "linux-gate\.so" > LIBS

# Find which libraries are included in the package. Binaries refer to
# libraries by their soname (e.g. libfoo.so.1), which is usually a
# symlink that isn't in the package (makepkg moves symlinks into
# doinst.sh), so use the soname recorded in each library, and the file
# name itself for libraries without one.
touch INCLUDED
find "$PKGROOT" -name "*.so*" | sed "s|.*/||" >> INCLUDED
# (LC_ALL, not LANG, since LC_ALL overrides LANG, and readelf's output is
# translated, e.g. "Bibliothèque soname" in French)
LC_ALL=C find "$PKGROOT" -type f -name "*.so*" -exec readelf -d {} + 2> /dev/null | \
sed -n "s/.*Library soname: \[\(.*\)\].*/\1/p" >> INCLUDED

# Exclude the included libs from the search list. ldd reports each
# library as the path where it was found, ending with its soname, or as
# "<soname> NOT FOUND".
awk 'FILENAME == "INCLUDED" { included[$0] = 1; next }
	{
		name = $0
		if (name ~ / NOT FOUND$/) {
			sub(/^[ \t]+/, "", name)
			sub(/ NOT FOUND$/, "", name)
		} else {
			sub(/.*\//, "", name)
		}
		if (!(name in included)) print
	}' INCLUDED LIBS > LIBS.new
mv LIBS.new LIBS

# Check if any dependencies are not found and bail out if they are
if [[ `grep "NOT FOUND" LIBS` ]]; then
	echo "ERROR: package requires libraries not found in the system:" >&2
	grep "NOT FOUND" LIBS |\
	sed "s/NOT FOUND//" |\
	sed "s/\t/ /" >&2
	if [ "x$DEPFINDERNOEXIT" != "x1" ]; then
		err
	fi
	# Carry on with the libraries that were found
	sed -i "/ NOT FOUND$/d" LIBS
fi

# Append the list of python modules to the list of libraries that are
# external dependencies
if [ $PYTHONDEPS -eq 1 ]; then
	cat PYTHONNEEDEDMODULES >> LIBS
fi

# Some files in /usr/lib have nasty paths like /usr/lib/../lib/
# as reported by ldd
sed -i "s|lib${LIBDIRSUFFIX}/\.\./||" LIBS

# Get the total number of libraries in the package 
TOTALLINES=`wc -l LIBS | sed "s/\(.*\) \(.*\)/\1/"`

# The number of jobs can not exceed the number of libraries present in
# the package and cannot be 0 either
[ $JOBS -gt $TOTALLINES ] && JOBS=$TOTALLINES
[ $TOTALLINES -eq 0 ] && JOBS=1

# Maximum file number should be $JOBS-1, split starts counting from 0
let MAXFILENO=$JOBS-1

# Split the libraries list in parts for running multiple jobs
let LINES=($TOTALLINES/$JOBS)+1
split -d -a 4 -l $LINES LIBS LIBS

# Find the dependencies (run multiple jobs if -j # is set)
for i in $( seq -f "%04.f" 0 $MAXFILENO ); do
	touch LIBS$i
	depfind $i &
done
wait
if ls FAILED[0-9]* > /dev/null 2>&1; then
	echo "ERROR: could not look up the libraries in the package database" >&2
	err
fi

# Put all dependencies in a single file
touch DEPS
for i in $( seq -f "%04.f" 0 $MAXFILENO ); do
	cat DEPS$i >> DEPS
done

# Warn about libraries (and python modules) that no installed package
# provides, e.g. ones installed by hand in /usr/local. They can't be
# added to the list, but the packager should know.
for i in $( seq -f "%04.f" 0 $MAXFILENO ); do
	sed "s|^/*|/|; s|^|WARNING: no installed package provides |" \
		UNOWNED$i >&2
done

# Exclude the present package from the dependency list, whatever
# version of it is installed, and drop entries left empty
awk -v self="$SELFNAME" '{
		n = split($0, alt, "|")
		line = ""
		for (j = 1; j <= n; j++) {
			name = alt[j]
			sub(/-[^-]*-[^-]*-[^-]*$/, "", name)
			if (self != "" && name == self) continue
			line = (line == "" ? alt[j] : line "|" alt[j])
		}
		if (line != "") print line
	}' DEPS > DEPS.new
mv DEPS.new DEPS

# Split each package into its name and version-arch-build (the last
# three parts separated by "-"; names may contain "-" too), and keep the
# name, or "name >= version-arch-build" with -s. (The list is sorted
# byte by byte, so it's in the same order whatever the locale.)
LC_ALL=C sort DEPS | uniq | \
awk -v versions=$VERSIONINFO '{
		n = split($0, alt, "|")
		line = ""
		for (j = 1; j <= n; j++) {
			name = alt[j]
			if (match(name, /-[^-]*-[^-]*-[^-]*$/)) {
				ver = substr(name, RSTART + 1)
				name = substr(name, 1, RSTART - 1)
				if (versions == 1) name = name " >= " ver
			}
			line = (j == 1 ? name : line "|" name)
		}
		print line
	}' > DEPSNAMES

# Output dependencies list
if [ $VERSIONINFO -eq 1 ]; then
	# If requesting version info, output the deps to a
	# slack-required file or to stdout
	if [ $CREATEDEPFILE -eq 1 ]; then
		if ! cp DEPSNAMES "$CWD/slack-required"; then
			echo "ERROR: could not write $CWD/slack-required" >&2
			err
		fi
	else
		cat DEPSNAMES
	fi
else
	# If not requesting version info, output the deps to a
	# .dep file or to stdout
	if [ $CREATEDEPFILE -eq 1 ]; then
		# (for a packaging directory, named after the package if
		# install/slack-desc names it, not after the directory)
		DEPFILENAME=$PKGNAME
		if [ -n "$STARTDIR" ] && [ -n "$SELFNAME" ]; then
			DEPFILENAME=$SELFNAME
		fi
		if ! cat DEPSNAMES | \
		   tr "\n" " " | \
		   sed "s/ /,/g" | \
		   sed "s/,$/\n/" | \
		   sed "s/^,//" > "$CWD/$DEPFILENAME.dep"; then
			echo "ERROR: could not write $CWD/$DEPFILENAME.dep" >&2
			err
		fi
	else
		cat DEPSNAMES | \
		tr "\n" " " | \
		sed "s/ /,/g" | \
		sed "s/,$/\n/" | \
		sed "s/^,//"
	fi
fi

# Clean up before exit
cleanup

