#!/bin/sh

# ----------------------------------
# which-package-provides.sh
# version 2.3.3.4
# ----------------------------------

if [ $# -lt 1 ]; then
  echo "Please specify the name of file(s); for example: '/bin/ls usr/lib/libm.so'."
  exit 1
fi

cd `dirname "${0}"`

[ -z "${BUILD_FARM}" ] && BUILD_FARM="${HOME}/build-farm"
if [ ! -d "${BUILD_FARM}" ]; then
  echo "ERROR: base directory '${BUILD_FARM}' doesn't exist. Abort."
  exit 1
fi

# check for required scripts
if [ ! -f ./generate_file_lists.sh ]; then
  echo "ERROR: build farm is broken; can't find script 'generate_file_lists.sh'. Abort."
  exit 1
fi

# generate lists
./generate_file_lists.sh

[ -z "${PACKAGES_DIR}" ] && PACKAGES_DIR="PACKAGES"

if [ -z ${ARCH_NAME} ]; then
  binpkg_dir=`find "${BUILD_FARM}/${PACKAGES_DIR}" -name "binpkg-*" | head -1`
  ARCH_NAME=`basename "${binpkg_dir}" | sed 's/binpkg-//'`
fi

[ -z "${BINPACKAGES_DIR}" ] && BINPACKAGES_DIR="${PACKAGES_DIR}"/binpkg-"${ARCH_NAME}"
[ -d "${BUILD_FARM}/${BINPACKAGES_DIR}" ] || BINPACKAGES_DIR="${PACKAGES_DIR}"/binpkg
if [ ! -d "${BUILD_FARM}/${BINPACKAGES_DIR}" ]; then
  echo "ERROR: binary packages directory '${BUILD_FARM}/${BINPACKAGES_DIR}' doesn't exist. Abort."
  exit 1
fi

for f_name in $@
do
  # trim leading '/' and './' (using ${f_name:1} and ${f_name:2} is considered as bashism)
  first_two_chars=`expr substr "${f_name}" 1 2`
  first_char=`expr substr "${f_name}" 1 1`
  [ ${first_char} = "/" ] && f_name=`echo "${f_name}" | sed 's/.\(.*\)/\1/'`
  [ ${first_two_chars} = "./" ] && f_name=`echo "${f_name}" | sed 's/^..//'`
  ##[ ${f_name:0:1} = "/" ] && f_name=${f_name:1}
  ##[ ${f_name:0:2} = "./" ] && f_name=${f_name:2}
  
  echo -n "searching for '/${f_name}'..."
  BINPKG_NAMES=""
  
  for curr_entry in "${BUILD_FARM}/${BINPACKAGES_DIR}"/.FILELISTS/*binpkg*
  do
    if [ -f "${curr_entry}" ]; then
      name_found=`cat "${curr_entry}" | grep -x "${f_name}"`
      if [ ! -z "${name_found}" ]; then
        BINPKG_NAMES="${curr_entry}:${BINPKG_NAMES}"
      fi
    fi
  done
  
  if [ -z "${BINPKG_NAMES}" ]; then
    echo " not found"
  else
    echo " found!"
    printf "/${f_name}:"
    BINPKG_NAMES=`echo "${BINPKG_NAMES}" | tr ':' '\n' | sort`
    echo "${BINPKG_NAMES}" | while read LINE
    do
      printf "\t%s\n" `basename "${LINE}" | sed 's/.list//'`
    done
  fi  
done
