#!/bin/bash
# Copyright 2015, 2016 Don March <don@ohspite.net>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

readonly help_msg="\
Usage: peeif [OPTION]... COMMAND...

Pipe a copy of STDIN to each COMMAND, but only if the exit status of the
previous command was zero.  The exit status of peeif is the exit status of the
last command that ran.

With the -u argument, the behavior is changed to \"peeuntil\", where each
command is run until one has an exit status of zero.

Options:
  -u  pipe STDIN to each COMMAND until receiving a nonzero exit status
  -n  do not use a temporary file to hold STDIN and instead use an environment
      variable
  -h  display this help and exit
  -v  output version and exit

STDIN is necessarily read and copied before being sent to any command.  By
default this is done with a temporary file; if STDIN will fit in a Bash
variable, you can use '-n' to avoid the creation of temporary files.
Depending on the system and the size of STDIN, it might be too big for a
variable to hold.

The name peeif comes from the pee command in moreutils, which is like tee but
for pipes.
"

readonly version_msg="\
peeif 0.1.1

Copyright 2016 Don March.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it. There is NO
WARRANTY, to the extent permitted by law.
"

not_being_sourced() {
  [[ "$0" == "${BASH_SOURCE[0]}" ]]
}

set -u
set -o pipefail

main() {
  parse_args "$@"

  if [[ "${use_tempfile}" == 1 ]]; then
    peeif_with_tempfile
  else
    peeif_with_var
  fi
}

peeif_with_tempfile() {
  tmpfile=$(mktemp --tmpdir "peeif.XXXXXX")
  trap 'rm "$tmpfile"' EXIT
  cat >"${tmpfile}"

  for cmd in "${commands[@]}"; do
    <"${tmpfile}" eval "${cmd}"
    local status="$?"
    if [[ "${pee_until}" == 1 ]]; then
      [[ "${status}" == 0 ]] && break
    else
      [[ "${status}" != 0 ]] && break
    fi
  done
  trap - EXIT
  rm "${tmpfile}"
  exit "${status}"
}

peeif_with_var() {
  # Read stdin into 'caught_stdin' without removing trailing newlines (which
  # happens with command substitution).
  set +e
  IFS= read -rd '' caught_stdin || true
  # Another way to do it is with this trick:
  # caught_stdin=$(cat; echo x)
  # caught_stdin=${caught_stdin%x}
  for cmd in "${commands[@]}"; do
    set +e
    printf '%s' "${caught_stdin}" | eval "${cmd}"
    local status="$?"
    if [[ "${pee_until}" == 1 ]]; then
      [[ "${status}" == 0 ]] && break
    else
      [[ "${status}" != 0 ]] && break
    fi
  done
  exit "${status}"
}

parse_args() {
  pee_until=0
  use_tempfile=1

  local OPTIND=1
  while getopts "nuhv" opt; do
    # shellcheck disable=SC2249
    case "${opt}" in
      u)
        pee_until=1
        ;;
      n)
        use_tempfile=0
        ;;
      h)
        show_help
        exit 0
        ;;
      v)
        show_version
        exit 0
        ;;
    esac
  done
  shift "$((OPTIND - 1))"
  [[ "$#" == 0 ]] && exit 0
  [[ "$1" = "--" ]] && shift
  [[ "$#" == 0 ]] && exit 0

  commands=("$@")
}

show_help() {
  printf '%s' "${help_msg}"
}

show_version() {
  printf '%s' "${version_msg}"
}

not_being_sourced && main "$@"
