#!/bin/sh

short_usage() {
  echo 'Usage: sor SNIPPET...'
}

help() {
  short_usage
  cat <<EOF
For each line from standard input, evaluate the specified SNIPPETs under Bash
with the line as the argument. Print the line if any snippet exits with
status 0.

      -0, --null             separate input and output filenames by null
      --help                 display this help and exit
EOF
}

ask_for_help() {
  echo "Try 'sor --help' for more information."
}

read_filename() {
  null_terminate=$1
  target_var=$2
  if [ "${null_terminate}" = true ]; then
    # shellcheck disable=SC3045
    IFS= read -r -d '' "${target_var}"
  else
    read -r "${target_var-}"
  fi
}

print_filename() {
  null_terminate=$1
  filename="$2"
  if [ "${null_terminate}" = true ]; then
    printf '%s\0' "${filename}"
  else
    echo "${filename}"
  fi
}

if ! temp=$(getopt -s bash -n sor -o 0 -l null,help -- "$@"); then
  ask_for_help >&2
  exit 1
fi
eval set -- "${temp}"
unset temp
null_terminate=false
while true; do
  case "$1" in
    --help)
      help
      exit 0
      ;;
    -0 | --null)
      shift
      null_terminate=true
      ;;
    --)
      shift
      break
      ;;
    *)
      echo >&2 'Internal error; please report.'
      exit 1
      ;;
  esac
done

while read_filename "${null_terminate}" file; do
  for test in "$@"; do
    if eval "${test} \"${file-}\""; then
      print_filename "${null_terminate}" "${file}"
      continue 2
    fi
  done
done
