#!/bin/bash
DIR=$(dirname "${BASH_SOURCE[0]}")

APPDIR="$HOME/.config/mira"
PKGCACHE="$APPDIR/packagelst.cache"
MIRAFINDBIN="$DIR/../../../bin/mirafind"

function findPackage()
{
	res=`sed -n -e "s/^$1 //p" $PKGCACHE`
	echo $res
}

function reindex()
{
	if [ ! -d $APPDIR ]
	then
		mkdir $APPDIR
	fi
	# create new cache as *.tmp file first, instead of overwriting the current
	# cache, to ensure that the old cache is preserved if the user presses
	# Ctrl+C during reindexing
	$MIRAFINDBIN -p > $PKGCACHE.tmp
	mv $PKGCACHE.tmp $PKGCACHE
}

if [[ $1 == "--reindex" ]];
then
	reindex
	exit 0
fi

if [ ! -f $PKGCACHE ];
then
	#cache does not exist, need to recreate it
	reindex
fi

if [[ -z "$1" ]];
then
	cat $PKGCACHE
else
	res=$(findPackage $1)
	if [[ -n "$res" ]];
	then
		# package found
		echo $res
	else
		# package not found, need reindex
		reindex
		res=$(findPackage $1)
		if [[ -n "$res" ]];
		then
			# package found
			echo $res
		else
			# package not found
			exit 255
		fi
	fi
fi





