#!/bin/sh -e
#
# what-provides - what package provides a binary in your path
#
# ---
# source: https://github.com/dustinkirkland/what-utils

# shellcheck disable=SC2312

. /etc/os-release 2>/dev/null || true
found=0

# Get package manager
if command -v "dpkg" >/dev/null 2>&1; then
  # Looks like we're in a Debian / Ubuntu system
  CMD="dpkg -S"
elif command -v "apk" >/dev/null 2>&1; then
  # Looks like we're in a Wolfi / Alpine system
  CMD="apk info --who-owns"
else
  exit 1
fi

# Get command-not-found
CNF=
for i in "/usr/lib/command-not-found" "/usr/libexec/command-not-found"; do
  if [ -x "${i}" ]; then
    CNF="${i}"
    break
  fi
done

# Look for our targets
for i in "$@"; do
  hit=0
  # First, check if it's an executable in our PATH
  if command -v "${i}" >/dev/null; then
    ${CMD} "$(readlink -f "$(command -v "${i}")")" && hit=1
  # Next, check if it's a path to a file
  elif [ -e "${i}" ]; then
    ${CMD} "$(readlink -f "${i}")" && hit=1
  # Or possibly an alias or something else
  elif type "${i}" >/dev/null; then
    type "${i}" && hit=1
  # Or otherwise, let's use locate to search the filesystem
  else
    for j in $(locate "${i}"); do
      ${CMD} "$(readlink -f "${j}")" || true
      found=1
    done
  fi
  # And if we still haven't found it, then let's search command-not-found
  if [ "${hit}" = "1" ]; then
    found=1
  elif [ -x "${CNF}" ]; then
    ${CNF} "${i}" && found=1
  fi
done

[ "${found}" = "1" ] || exit 1
