#!/usr/bin/sh
##
## Solaris pwait(1) clone for Linux, AIX
## Copyright (c) 2012-2018 SATOH Fumiyasu @ OSS Technology Corp., Japan
##               <https://github.com/fumiyas/home-commands/blob/master/pwait>
##               <https://fumiyas.github.io/>
##
## License: GNU General Public License version 3
##

perr()
{
  echo "$0: ERROR: $1" 1>&2
}

verbose_p=""
poll_interval="${PWAIT_POLL_INTERVAL:-10}"

if [ "${1-}" = "-v" ]; then
  verbose_p="set"
  shift
fi

if [ $# -eq 0 ]; then
  echo "Usage: $0 [-v] PID ..."
  exit 1
fi

if type inotifywait >/dev/null 2>&1; then
  inotifywait="set"
else
  inotifywait=""
fi

trap 'rc=$?; trap "" TERM; kill -TERM -$$; exit $rc' EXIT

for pid in "$@"; do
  if ! cd "/proc/$pid" 2>/dev/null; then
    perr "No such process: $pid"
    continue
  fi

  (
    [ -r exe ] || inotifywait=""
    if [ -n "$inotifywait" ]; then
      set -- inotifywait --quiet --event close_nowrite exe
    else
      set -- sleep "$poll_interval"
    fi
    while :; do
      "$@" >/dev/null
      if ! cd . 2>/dev/null; then
	[ -n "$verbose_p" ] && echo "$pid: terminated"
	exit 0
      fi
    done
  ) &
done

wait
