#!/bin/sh
# This program generates the index file to be used in dpkg-query
# It currently works using arrow, but can be modified to use
# remembrance-agent instead

# TODO: make it work with both by checking which one is available

# ------------------------------------------------------------------
# This  program can work with remembance-agent,
# set INDEX=/usr/bin/ra-index
# This requires the remembrance-agent program, by MIT, to work
# And the template for DEBIAN PACKAGES in the configuration file
# (savant.rc), which is:
#TEMPLATE DEBIAN-PACKAGE
#{
#   Recognize { startline, "Package:"}
#   Format   {
#             {anyorder optional {startline, "Maintainer: ", SOURCE, "\n"},
#                      optional {startline, "Date: ", DATE, "\n"},
#                      optional {startline, "Description: ", SUBJECT, "\n"}}
#              startline, BODY}
#}

# Global variables
PROGRAM_BREAK=/usr/bin/dpkg2folder
# For remembrance-agent USE
# PROGRAM_BREAK=/usr/bin/dpkg-break
INDEX=/usr/bin/arrow
DPKG_INDEX_DIR=/var/lib/dpkg/index.db
DPKG_AVAILABLE=/var/lib/dpkg/available
TMP_DIR=`tempfile -d /var/tmp/`
NAME="dpkg-make-index"
usage="Usage: $NAME [-vd]\n
\040\040-v\040\040Verbose\n
\040\040-d\040\040Print debugging information"

if [ "`whoami`" != "root" ]; then
	echo "Sorry, dpkg-make-index must be run as Root."
	exit 1
fi

# Scan for options
while getopts vd option; do 
	case $option in
	v)	VERBOSE=$option
		;;
	d)	DEBUG=$option
		;;
	\?)	echo $usage
		exit 1
		;;
	esac
done



# first make in a temporal directory a breakout of all packages
# available
if [ -e $TMP_DIR ]; then
	/bin/rm -rf $TMP_DIR | exit 1
fi
mkdir $TMP_DIR
if [ ! -d $DPKG_INDEX_DIR ]; then
	mkdir $DPKG_INDEX_DIR;
fi
cd $TMP_DIR;
/bin/echo "Breaking the database into files..."
$PROGRAM_BREAK <$DPKG_AVAILABLE
/bin/echo "Indexing database ..."
OPTS="-v 1"
if [ "$VERBOSE" = "v" ]; then
	OPTS="-v 2"
fi
if [ "$DEBUG" = "d" ]; then
	OPTS="-v 3"
fi
# For remembrance-agent (removed since it is non-free)
# TODO: change this when remembrance-agent is moved to main
#$INDEX $OPTS -c $CONF_FILE $DPKG_INDEX_DIR $TMP_DIR

# Using libbow (arrow)

cd $TMP_DIR && $INDEX $OPTS --data-dir=$DPKG_INDEX_DIR . && cd -

# Patch sent by Jonathan H N Chin for bug #86732
# However, it does not index properly all the directories
# /bin/find $TMP_DIR/ -type d -print | xargs -r $INDEX $OPTS  --data-dir=$DPKG_INDEX_DIR


/bin/echo "Cleaning temporary directory."
/bin/rm -rf $TMP_DIR/
/bin/echo "Finished.. try dpkg-query to make a query and dpkg-make-index to rebuild the database."
