#!/bin/sh
#
# Copyright (C) 2012  Etersoft
# Copyright (C) 2012  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# TODO: port or rewrite apt-file
# https://bugzilla.altlinux.org/show_bug.cgi?id=14449
local_content_search()
{
    local SYSARCH
    SYSARCH=$(uname -m)
    [ "$SYSARCH" = "x86_64" ] || SYSARCH=i586

    local REPODIR=/var/ftp/pub/ALTLinux/Sisyphus
    local CI=$REPODIR/$SYSARCH/base/contents_index
    local CINOA=$REPODIR/noarch/base/contents_index
    #local OUTCMD="less"
    #[ -n "$USETTY" ] || OUTCMD="cat"
    OUTCMD="cat"

    test -r $CI && test -r $CINOA || fatal "Can't locate $CI or $CINOA"

    {
        [ -n "$USETTY" ] && echo "Search in $CI and $CINOA for $1..."
        grep -h -- ".*$1.*\t" $CI $CINOA | sed -e "s|\(.*\)\t\(.*\)|\2: \1|g"
    } | $OUTCMD
}

epm_search_file()
{
	local CMD
	[ -n "$pkg_filenames" ] || fatal "Run search without names"

case $PMTYPE in
	apt-rpm)
		local_content_search $pkg_filenames
		return ;;
	apt-dpkg)
		sudocmd apt-file update
		docmd apt-file search $pkg_filenames
		return ;;
	yum-rpm)
		CMD="yum provides"
		;;
	dnf-rpm)
		CMD="dnf provides"
		;;
	urpm-rpm)
		CMD="urpmf"
		;;
	zypper-rpm)
		CMD="zypper wp vi"
		;;
	pacman)
		CMD="pacman -Qo"
		;;
	slackpkg)
		CMD="/usr/sbin/slackpkg file-search"
		;;
	ipkg)
		CMD="ipkg search"
		;;
	*)
		fatal "Have no suitable search file command for $PMTYPE"
		;;
esac

docmd $CMD $pkg_filenames

}