#!/bin/sh
#
# Kills all non-system processes that aren't owned by a logged in user as
# returned by who.

# kills a given process
kill_proc()
{
  ps awwux | egrep '^[a-z0-9A-Z]+ *'$1' '
  kill $1 >/dev/null 2>&1	# first try to close it gracefully
  sleep 1			# give it a second to die nicely
  kill -9 $1 >/dev/null 2>&1	# but if it is still around, kill it dead
}

# builds the string used by egrep to filter out processes owned by valid users
build_user_string()
{
   user_string='^(USER|root|daemon|kmem|bind'
   for user in `who | cut -f 1 -d ' '`
   do
      user_string="$user_string|$user"
   done
   user_string="$user_string)"
}

# lists all invalid processes
list_invalid_procs()
{
   if [ ! -n "$user_string" ]; then
      build_user_string
   fi
   ps awwux | head -1		# get the ps header...
   ps awwux | egrep -v $user_string
}

# builds list of invalid processes and kills them
kill_invalid_procs()
{
   if [ ! -n "$user_string" ]; then
      build_user_string
   fi
   bad_procs=`ps auxw | egrep -v $user_string | awk '{ print $2 }'`
   for proc in $bad_procs
   do
      kill_proc $proc
   done
}

# main function for killresidentprocs
kill_resident_procs()
{
   echo
   echo "Killing all non-system processes not owned by a logged in user."
   ps awwux | head -1		# get the ps header...
   kill_invalid_procs

   echo "Letting processes die..."
   sleep 2

   echo
   echo "These processes wouldn't die:"
   list_invalid_procs
}

# main function for listresidentprocs
list_resident_procs()
{
   echo "These processes are not owned by root, daemon, kmem, or a logged in user:"
   list_invalid_procs
}

# ----------------------------------------------------------------------------
# entry point

case `basename $0` in 
   kill*)
      kill_resident_procs
      ;;
   list*)
      list_resident_procs
      ;;
   *)
      echo 'Usage:  <kill|list>residentprocs'
      echo
      echo 'If called as "listresidentprocs", this script lists all resident procs that are'
      echo 'not system processes owned by a user who is not logged in.'
      echo
      echo 'If called as "killresidentprocs", this script first tries to kill all of the'
      echo '"bad"' "processes and then lists those that wouldn't die."
esac

exit 0
