#!/bin/sh
#
# This script provides a suitable output for the search results.
#

# Clean preview results.
rm -f /tmp/tazpkgbox/search
touch /tmp/tazpkgbox/search

list_files()
{
	sed 's/.\[[01]m//g' | awk 'BEGIN { show=0 } {
		if (/^===/) show=1-show;
		else if (/^Package/) pkg=$2;
		else if ($0 != "" && show != 0) printf("%s %s\n",pkg,$0);
	}' | while read pkg file; do
		[ "$pkg" = "0" ] && continue
		version=$(grep -hs "^$pkg " /var/lib/tazpkg/packages.desc \
		  /var/lib/tazpkg/undigest/*/packages.desc | awk '{ print $3 }')
		if [ -d /var/lib/tazpkg/installed/$pkg ]; then
			if [ -x $file ]; then
				echo "exec|$pkg|$version|$file"
			elif [ -f $file ]; then
				echo "txt|$pkg|$version|$file"
			elif [ -d $file ] ; then
				echo "folder|$pkg|$version|$file"
			else
				# Missing installed file.
				echo "dialog-warning|$pkg|$version|$file"
			fi
		else
			echo "tazpkg|$pkg|$version|$file"
		fi
	done
}

search_package()
{
	IFS="|"
	cat /var/lib/tazpkg/packages.desc \
	    /var/lib/tazpkg/undigest/*/packages.desc 2> /dev/null | sort | \
	while read PACKAGE VERSION SHORT_DESC; do
	if echo "$PACKAGE $SHORT_DESC" | grep -q "$SEARCH"; then
		if [ -d /var/lib/tazpkg/installed/${PACKAGE%% *} ]; then
			. /var/lib/tazpkg/installed/${PACKAGE%% *}/receipt
			echo "tazpkg-installed|$PACKAGE|$VERSION|$SHORT_DESC"
		else
			echo "tazpkg|$PACKAGE|$VERSION|$SHORT_DESC"
		fi
	fi
	done 
	unset IFS
}

case "$1" in
	files)
		tazpkg search-file "$SEARCH" --mirror | list_files > \
			/tmp/tazpkgbox/search ;;
	packages)
		search_package > /tmp/tazpkgbox/search ;;
	*)
		echo "Usage: $0 [packages|files]" ;;
esac


exit 0
