#!/bin/sh
#####
# NAME
#	search-package - search package tarball file
# VERSION
#	$Id$
# CHANGELOG
#	$Log$
# USAGE
#	search-package topdir package
# DESCRIPTION
#  Search-package command search the tarball file under the "topdir" directory.
#  The target package name is given by "package".
# COPYRIGHT
#  Copyright (C) 2000,2001,2002 Steel Wheels Project.
#  This file is a apart of the papaya utilities. 
#  If you need the information of copyright of this file, see COPYING
#  file distributed with file or see http://www.asahi-net.or.jp/~em7t-hmd
#  web page.

this="search-package"

error(){
	echo "$this [ERROR] $*" 1>&2 ;
	exit 1 ;
}

message(){
	echo "$this: $*" 1>&2 ;
}

check_arg(){
	if [ "x$1" = "x" ] ; then
		echo "$this [ERROR] argument is missing" 1>&2
		echo "usage: search-package topdir package" 1>&2
		exit 1
	fi
}

topdir=$1 ; package=$2 ;

check_arg $topdir 
check_arg $package

if [ ! -d $topdir ] ; then
	error "$this [ERROR] directory \"$topdir\" is not found."
fi

file_list1=`find $topdir -type f -print | grep "/${package}[-_][^/]*$"`
file_list2=`find $topdir -type f -print | grep "^${package}[-_][^/]*$"`

result=""
for filename in $file_list1 $file_list2 ; do
	# echo "filename: $filename" ;
	if [ "x$result" = "x" ] ; then
		result=$filename
	else
		resver=`get-package-version $result`
		if [ -z $resver ] ; then
			error "failed to get version of \"$result\""
		fi
		filever=`get-package-version $filename`
		if [ -z $filever ] ; then
			error "failed to get version of \"$filename\""
		fi

		if compare-version $resver $filever ; then
			message "choose $result instead of $filename" ;
		else
			message "choose $filename instead of $result" ;
			result=$filename ;
		fi
	fi
done

echo $result 

exit 0 

