#!/usr/bin/env sh
#
# run-after - check if correct number of arguments are provided
# dependencies: fzy (fzf)
#
# ---
# source: https://github.com/jayghoshter/dotfiles

if [ "$#" -lt 2 ]; then
  echo "Usage: $(basename "$0") <process_name> <command>"
  exit 1
fi

process_name="$1"
shift
command_to_run="$1"
shift

if command -v fzy >/dev/null 2>&1; then
  pid=$(ps x -ao pid,command | grep -v grep | grep "${process_name}" \
    | fzy -p 'Processes > ' | awk '{ print $1 }')

elif command -v fzf >/dev/null 2>&1; then
  pid=$(pgrep -fa "${process_name}" | sed 1d \
    | fzf --preview="ps -p {1}" --preview-window='down:3:nohidden' \
    | awk '{ print $1 }')
fi

[ -n "${pid}" ] || exit 1

# wait for the process to complete
while ps -p "${pid}" >/dev/null 2>&1; do
  printf "\r%s" "Waiting for process '${process_name}' to complete..."
  sleep 1
done

printf "\n"
echo "Process '${process_name}' has completed. \
  Executing command: ${command_to_run} $*"
# execute the command
eval "${command_to_run}" "$*"
