#!/bin/sh -e
#
# ,wait-for-completion - wait for a process to exit and then run something

# get process listing with compatible fields on both Linux and macOS
# shellcheck disable=SC2312
if [ "$(uname)" = "Darwin" ]; then
  # tail -n+8: drop the ones started by this script
  psp="$(ps -ewwo user,pid,start,command | tail -n+2 | tac \
    | grep "${LOGNAME:-${USER-}}" | tail -n+8 | fzf --query "$*")"
  procpid="$(echo "${psp}" | awk '{ print $2 }')"
  procname="$(echo "${psp}" | awk '{ out=$4; for(i=5; i<=NF; i++){ out=out" "$i }; print out }')"
else
  psp="$(ps -elf --sort=start_time | tac | grep "${LOGNAME:-${USER-}}" \
    | tail -n+8 | fzf --query "$*")"
  procpid="$(echo "${psp}" | awk '{ print $4 }')"
  procname="$(echo "${psp}" | awk '{ out=$15; for(i=16; i<=NF; i++){ out=out" "$i }; print out }')"
fi

echo "Waiting for" "${procname}"
# see: https://ao.bloat.cat/questions/1058047/placeholder#41613532
tail --pid="${procpid}" -f /dev/null
