#!/usr/bin/env bash
set -euo pipefail

# Script Name: waitfor
# Description: Wait for process to complete (useful for automation chains)
# Source: https://evanhahn.com/scripts-i-wrote-that-i-use-all-the-time/
# Credit: Evan Hahn - https://codeberg.org/EvanHahn/dotfiles
# Usage: long-running-cmd & waitfor $!        # wait for background job
#        waitfor 1234                         # wait for specific PID
#        waitfor 1234 && notify "Job done!"   # chain operations

if [[ $# -eq 0 ]]; then
  echo "Usage: waitfor <PID>" >&2
  echo "Example: firefox & waitfor \$!" >&2
  exit 1
fi

pid=$1

if ! ps -p "$pid" > /dev/null 2>&1; then
  echo "Process $pid not found or already completed" >&2
  exit 1
fi

process_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
echo "Waiting for $process_name (PID: $pid) to complete..."

# Strategy 1: systemd-inhibit (Linux - prevents sleep)
if command -v systemd-inhibit &>/dev/null; then
  systemd-inhibit --what=sleep --who="waitfor" \
    --why="Waiting for PID $pid ($process_name)" \
    tail --pid="$pid" -f /dev/null 2>/dev/null
# Strategy 2: caffeinate (macOS - prevents sleep)
elif command -v caffeinate &>/dev/null; then
  caffeinate -w "$pid"
# Strategy 3: Simple polling (fallback)
else
  tail --pid="$pid" -f /dev/null 2>/dev/null || {
    # If tail doesn't support --pid, use manual polling
    while ps -p "$pid" > /dev/null 2>&1; do
      sleep 1
    done
  }
fi

echo "✓ Process $pid completed"
