#!/bin/sh
#
# mex - make the first non-executable instance of files with the given names
# in $PATH executable
#
# Iterate through the directories named in $PATH looking for files with any of
# the specified names that do not have the executable permissions bit set, and
# attempt to set them if any such files are found. Exit nonzero if any of the
# names were not found, or if any of the permissions changes failed.
#
# Usage:
#     mex name
#     mex name1 name2 name3
#     PATH=/foo:/bar/baz mex name

self=mex

# check we have at least one argument
if [ "$#" -eq 0 ]; then
  printf >&2 '%s: At least one name required\n' "${self}"
  exit 2
fi

# iterate through the given names
for name; do

  # clear the found variable
  found=

  # start iterating through $PATH, with colon prefix/suffix to correctly
  # handle the fenceposts
  # shellcheck disable=SC2250
  path=:$PATH:
  while [ -n "${path}" ]; do

    # pop the first directory off $path into $dir
    dir=${path%%:*}
    path=${path#*:}

    # check $dir is non-null
    [ -n "${dir}" ] || continue

    # if a file with the needed name exists in the directory and isn't
    # executable, we've found our candidate and can stop iterating
    if [ -f "${dir}"/"${name}" ] && ! [ -x "${dir}"/"${name}" ]; then
      found=${dir}/${name}
      break
    fi
  done

  # if the "found" variable was defined to something, we'll try to change its
  # permissions
  if [ -n "${found}" ]; then
    case ${found} in
      /*) ;;
      *) found=${PWD}/${found} ;;
    esac
    chmod +x "${found}" || ex=1

  # if not, we'll report that we couldn't find it, and flag an error for the
  # exit status
  else
    printf >&2 '%s: No non-executable name "%s" in PATH\n' "${self}" "${name}"
    ex=1
  fi
done

# we exit 1 if any of the names weren't found or if changing their permissions
# failed
exit "${ex:-0}"
