#!/bin/bash
# This script provides a simple, single command look up of which package
# owns a file. It currently knows about rpm on Redhat and dpkg on Debian.
# Version: 0.1
# Dean Wilson (2005/03/17)

# get and confirm we have a filename passed in.

#see if they want to go to locate right away.
if [ $# -eq 2 ];then
  if [ "$1" = "-l" ];then
    uselocate=1
  else
    echo "usage: $0 [-l] filename"
    exit 1
  fi
  filename=$2
else
  uselocate=0
  filename=$1
fi

# sanity check filename
if [ -z "$filename" ];then
  printf "$0: No filename passed in.\n"
  exit 2
fi



# get the full path to pass to the pkg system
fullpath=$(which $filename | tr -d '\n')
whichret=$?

if [ -z "$fullpath" ] || [ "$whichret" -ne 0 ];then
  whichfail=1
else
  whichfail=0
fi

# if which fails then it might not be a binary. try locate.
# also try locate if the -l flag was passed ($uselocate is set)
if [ "$whichfail" -ne "0" ] || [ "$uselocate" -ne "0" ];then
  fullpath=$(locate $filename && head -n 1)
  locateret=$?

  if [ "$locateret" -ne 0 ];then
    echo "locate had problems finding '$filename'..."
    exit 3
  fi
fi


# look for /etc/redhat_release /etc/debian_version or FreeBSD in the uname.

if [ -e "/etc/redhat-release" ];then
  OS="redhat"
elif [ -e "/etc/debian_version" ];then
  OS="debian"
else
  echo "Not sure which platform I'm running on. Exiting..."
  exit 4
fi



# run the required command to get the owning package.
if [ "$OS" == "redhat" ];then
  pkgname=$(rpm -qf $fullpath)
elif [ "$OS" == "debian" ];then
  pkgname=$(dpkg -S $fullpath)
else
  echo "Don't understand this platform. Exiting..."
  exit 5
fi


# print the answer and exit nicely
echo "$filename is owned by $pkgname"
exit 0
