#!/bin/bash

# Turn off slower check.
PERFORM_SLOWER_CHECK=0

# How long to delay PassengerHelperAgent ps commands.
passenger_delay_ps=6

function checkParentIsPassengerHelperAgent() {
   # Get parent pid and command.
   [ -n "$PPID" ]  &&  p_cmd=`/bin/ps -p $PPID --no-heading -o cmd 2> /dev/null`

   # Check if parent command is PassengerHelperAgent.
   [ "$p_cmd" = "PassengerHelperAgent" ]  &&  return 0
   return 1
}

function isParentPassenger() {
   # Args that the PassengerHelperAgent passes.
   passenger_cmd_args="-o pid,ppid,%cpu,rss,vsize,pgid,command"

   #  Optimized check - may catch false positives - will work, just a lil'
   #  bit delayed. Needs of the many passenger procs outweigh the needs of
   #  the few [ps calls issued w/ matching args].
   if echo "$@" | egrep -e "$passenger_cmd_args" > /dev/null 2>&1; then
      return 0
   fi

   # Slower but better check which checks parent if PassengerHelperAgent.
   if test "$PERFORM_SLOWER_CHECK" -eq "1"; then
      checkParentIsPassengerHelperAgent
      return $?
   fi

   return 1
}


# Get parent pid and command -- if its PassengerHelperAgent that issued
# the ps, then renice and throttle the command (sleep a bit).
{
   if isParentPassenger "$@"; then
      # Perl's sleep uses sigalrm and is the best of the lot - use some
      # randomness though.
      case "$((RANDOM % 5))" in
         0) ;;  #  run immediately
         2) sleep 1;;
         *) perl -e "sleep $passenger_delay_ps";;
      esac
   fi
} > /dev/null 2>&1

exec /bin/ps "$@"
