#! /bin/sh

# Exit on error and disable globing
set -ef

Usage() {
  printf "usage: $0 [-a] name ...\n" >&2
  exit 1
}

# Arguments -a
ALLMATCHES=0
# Number of elements that were not found
NOTFOUND=0
# Default OpenBSD PATH
DEFAULT_PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin"

# # Parse the parameters to find -a and avoid getopt output on invalid argument
# args=`getopt a $* 2> /dev/null`
# if [ $? -ne 0 ]
# then
#     Usage
# fi

# Parse the parameters, ignoring the parameters  after the first argument
while getopts a whichopts; do
  case "$whichopts" in
  a) ALLMATCHES=1 ;;
  ?) Usage ;;
  esac
done
# Skip the parsed parameters
shift $(($OPTIND - 1))

# If no arguments provided, prints the usage
if [ "$#" -eq 0 ]; then
  Usage
fi

if [ -z "$PATH" ]; then
  PATH="$DEFAULT_PATH"
fi

for PROGRAM in "$@"; do
  FOUND=0

  # Save the IFS and set it to : to split the PATH
  SAVE_IFS="$IFS"
  IFS=:

  # If the program contains a /, we check if it is a file and executable
  # otherwise we check in the PATH
  case $PROGRAM in
  */*)
    if [ -f "$PROGRAM" ] && [ -x "$PROGRAM" ]; then
      printf "$PROGRAM\n"
    fi
    ;;
  *)
    for ELEMENT in $PATH; do
      # If an element in path is empty (/path::/other/path)
      # We check the current directory
      if [ -z "$ELEMENT" ]; then
        ELEMENT=.
      fi

      # Trim trailing /
      ELEMENT="${ELEMENT%/}"

      if [ -f "$ELEMENT/$PROGRAM" ] && [ -x "$ELEMENT/$PROGRAM" ]; then
        FOUND=1
        printf "$ELEMENT/$PROGRAM\n"
        # If -a provided we continue, otherwise we break after the first match
        [ "$ALLMATCHES" -eq 1 ] || break
      fi
    done
    ;;
  esac

  # Restore the IFS (inside the loop to have the correct behavior
  # while splitting the arguments)
  IFS="$SAVE_IFS"

  # If the program was not found, we print an error message
  if [ "$FOUND" -eq 0 ]; then
    printf "%s: %s: Command not found.\n" "$0" "$PROGRAM" >&2
    NOTFOUND=$((NOTFOUND + 1))
  fi
done

# If none of the programs were found, we exit with 2, otherwise if some were
# found we exit with 1 and if all were found we exit with 0
if [ "$NOTFOUND" -eq "$#" ]; then
  exit 2
elif [ "$NOTFOUND" -ne 0 ]; then
  exit 1
fi

exit 0
