#!/bin/bash
#
# garfind
#
# find packages in the gar directory structure
#
#

VERSION=1.0.0
DATE=20190818

[[ "$GARDIR" ]] || GARDIR=/usr/gar

display_usage () {
   echo
   echo "garfind $VERSION ($DATE)"
   echo
   echo "Usage: $(basename $0) [-k] <name>"
   echo
   echo "$(basename $0) searches the gar directory structure for package"
   echo "directories named <name>. <name> is subject to fnmatch(3) pattern"
   echo "matching."
   echo
   echo " Options:"
   echo
   echo " -k Search for package categories instead of package names"
   echo " -p Show the full path of items found instead of displaying"
   echo "    their path relative to the gar root directory ($GARDIR)"
   echo " -V Display the program version"
   echo
   echo "Examples:"
   echo
   echo "$(basename $0) 'linux'"
   echo "$(basename $0) 'linux-*'"
   echo "$(basename $0) -k '*util*'"
   echo
}


##### Defaults #####
# Category search?
catsearch=0

# Display full path?
fullpath=0

#######################################################
#                 Options processing                  #
#######################################################

while getopts ":Vkp" opt; do
  case $opt in
    V)
      echo "$(basename $0) $VERSION, $DATE"
      exit 0
      ;;
    k)
      catsearch=1
      ;;
    p)
      fullpath=1
      ;;
    \?)
      echo "$(basename $0): Invalid option: -$OPTARG" >&2
      display_usage
      exit 1
      ;;
    :)
      echo "$(basename $0): Option -$OPTARG requires an argument" >&2
      exit 1
      ;;
  esac
done

shift $(($OPTIND-1))

##### Positional arguments processing #####

if [[ -z "$1" ]]; then
   display_usage
fi

needle="$1"

###########################################

display_item () {
   if [[ $fullpath -eq 1 ]]; then
      echo $@
   else
      echo $@ | sed "s%${GARDIR}%%g; s%^/%%g;"
   fi
}

main () {


   if [[ $catsearch -eq 0 ]]; then
      find "${GARDIR}/" -maxdepth 5 -type d -name "${needle}" | while read n; do
          [[ -f "${n}/config.mk" ]] && display_item "${n}"
      done
   else
      find "${GARDIR}/" -maxdepth 5 -type d -path "${GARDIR}/${needle}" | while read n; do
         [[ -L "${n}/level.mk" ]] && display_item "${n}"
      done
   fi
}

main
