#!/usr/bin/env bash

set -x

add_background_process="${1}"
try_wait_n="${2}"
enable_lastpipe="${3}"

if [[ ${enable_lastpipe} == 'true' ]]; then
  shopt -s lastpipe
fi

declare -a pid=()
: <( sleep 4; ); pid+=( ${!} )
: <( sleep 6; ); pid+=( ${!} )
: <( sleep 8; ); pid+=( ${!} )
: <( sleep 10; ); pid+=( ${!} )
if [[ ${add_background_process} == 'true' ]]; then
  sleep 1 & pid+=( ${!} )
fi
: <( sleep 2; ); pid+=( ${!} )
SECONDS=0
: "${pid[*]@A}"
wait -- "${pid[0]}"
: termination status ${?} at ${SECONDS} seconds
if [[ ${try_wait_n} == 'true' ]]; then
  wait -n -p completed_pid -- "${pid[@]}"
  : termination status ${?} at ${SECONDS} seconds
  : completed_pid=${completed_pid}
fi
wait
: termination status ${?} at ${SECONDS} seconds
wait -- "${pid[@]}"
: termination status ${?} at ${SECONDS} seconds
