#!/bin/sh

# Written by Sergio Vicari (2016) <sercari@esdebian.org>

# findpkg: Find installed Slackware packages.

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

echo -e
printf "findpkg: Find Slackware packages installed or file in the content thereof.
Usage: 
findpkg <package_filename> or part of this. (search one package)
findpkg <package_filename>(,) <2pkg_filename>(,) <...> (search some packages)
findpkg -i (--into) <filename> (search file in packages)

"

DACT=$(pwd)
if [ "$1" = -i ] || [ "$1" = --into ]; then
INTO=$(echo $2 |wc -w)
    if [ "$INTO" = 0 ]; then
       echo ERROR: Must be specified a valid filename.
       echo -e 
       exit 0
    else
       echo For \"$2\" inside packages the following results were found:
       cd /var/log/packages/
       grep -i "/$2$" * -R
       cd $DACT
       echo -e
       exit 0
    fi
else
    if [ "$#" = 0 ]; then
       echo ERROR: Must be specified a package name.
       echo -e 
       exit 0
    else
       for i in `echo $* |sed -e 's/,/ /g'`
       do
          PKGFIND=$(ls /var/log/packages/ |sed -e 's/,/ /g' |grep -i $i 2>/dev/null)
          if [ -z "$PKGFIND" ] ; then
             echo For \"$i\" the following results were found:
             echo No matches were found.
             echo -e
          else
             echo For \"$i\" the following results were found:
             ls /var/log/packages/ | grep -i $i 2>/dev/null
             echo -e
          fi
       done
       exit 0
     fi
fi
exit
