#!/usr/bin/env bash
# Desc: Reads stdin and positional arguments

yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
read_stdin_psarg() {
    # Desc: Consumes stdin and reads arguments; outputs as stdout lines
    # Input: stdin (consumes)
    # Input: args
    # Output: stdout (newline delimited)
    # Example: read_stdin_psarg "$@"
    # Depends: GNU bash (version 5.1.16)
    # Version: 0.0.3
    local input_stdin input_psarg output;

    # Store stdin
    if [[ -p /dev/stdin ]]; then
        input_stdin="$(cat -)";
    fi;
    
    # Store arguments
    if [[ $# -gt 0 ]]; then
        input_psarg="$*";
    fi;
    
    # Combine as output array elements
    ## Read in stdin
    if [[ -n $input_stdin ]]; then
        while read -r line; do
            output+=("$line");
        done < <(printf "%s\n" "$input_stdin");
    fi;
    ## Read in positional arguments
    if [[ -n $input_psarg ]]; then
        for arg in "$@"; do
            output+=("$arg");
        done;
    fi;

    # Print to stdout
    printf "%s\n" "${output[@]}";
}; # read stdin and positional argument to stdout lines
main() {
    read_stdin_psarg "$@";
};

main "$@";