#!/bin/bash

# build the database

CWD=$(dirname $0)
UNPACKDIR=$CWD/package$$
DB=/var/cache/packages/db

SLACKWARE="$1"
if [ "$SLACKWARE" = "" ]; then
   SLACKWARE=/media/cdrom/slackware64
fi

if [ ! -r "$SLACKWARE/MANIFEST.bz2" ]; then
   echo "Create database with Slackware files and their dependencies"
   echo "Database goes to $DB"
   echo ""
   echo "   usage: $0   [ SLACKWARE_DVD ]"
   echo ""
   exit 1
fi

detect_shell()
{
   while [ "$1" ]; do
     head -n 1 "$1" | grep "^#!/" | sed -r 's:(/usr)?/bin/env[[:space:]]+::g' | sed -r 's/..([^[:space:]]+).*/\1/' \
     | xargs -r -I @@@@ echo -e "$1\0@@@@"
     shift
   done
}

export -f detect_shell

echo "===================================================================="
echo "Processing Slackware packages from: $SLACKWARE"
echo "This can take several hours"
echo "===================================================================="

mkdir -p $DB

find "$SLACKWARE" -name *.txz | while read LINE; do

   echo "Processing $LINE ..."
   OUT="$TMPDB/$(basename "$LINE")"

   rm -Rf "$UNPACKDIR"
   mkdir -p "$UNPACKDIR"

   tar -xf "$LINE" -C "$UNPACKDIR" >/dev/null 2>&1 || exit 1
   (cd "$UNPACKDIR"; sh install/doinst.sh) >/dev/null 2>&1
   rm -Rf "$UNPACKDIR/install"

   # find all regular files and links
   find $UNPACKDIR -xdev ! -type d | egrep -v "^[.]\$" | grep -v "^$UNPACKDIR\$" | sed -r "s:^$UNPACKDIR/:fos\\::" >"$OUT"

   # find library dependencies
   rm -Rf $UNPACKDIR/usr/doc
   find "$UNPACKDIR" -xdev -type f | while read FILE; do
      ldd "$FILE" 2>/dev/null | egrep '^\s' | sed -r 's/\t| =>.*| \(.*//g' | grep -av '^linux-gate.so' \
      | xargs -r -I @@@@ echo -e "$FILE\0@@@@" \
      | egrep -av 'not a dynamic executable|statically linked' | sed -r "s:^$UNPACKDIR/?:dep\\::"
   done >>"$OUT"

   # find all script (interpreter) dependencies
   find "$UNPACKDIR" -xdev -type f -print0 | xargs -0 -r file | fgrep script | fgrep text | cut -d: -f1 \
      | xargs -n 1 -d "\\n" bash -c 'detect_shell "$@"' _ \
      | sort | uniq | sed -r "s:^$UNPACKDIR/:dep\\::" >>"$OUT"

   rm -Rf "$UNPACKDIR"

done

