#!/usr/bin/env bash

set -x

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

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
declare -p pid
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"
  declare -p completed_pid
fi
wait
: "termination status ${?} at ${SECONDS} seconds"
wait -- "${pid[@]}"
: "termination status ${?} at ${SECONDS} seconds"
