#!/bin/sh -f
#    File: $CVSROOT/IDEA-DEV/Tools/Scripts/clean-sandbox
#    Date: Tue Nov 15 09:53:01 2005
#     CVS: $Id: clean-sandbox,v 1.1 2005/11/15 17:53:57 plaunt Exp $
# Purpose: kill any remaining processes accociated with a prior run by
#          the user calling this script, and clean up the system wide
#          shared memory and semaphore resource thereunto pertaining.

# helper fn
usage ()
{
  echo " "
  echo "usage: $0"
  echo " "
}

if [ $# -ne 0 ]
then
  usage
  exit
fi

echo "Cleaning up the sandbox..."

# herein lie the names of the process which may not yet be dead.  add
# 'em if you got 'em.

errant_procs=`echo timingservice_sh`

kill_errant_proc ()
{
  temp_pid=`ps | egrep $1 | gawk '{ print $1 }'`
  if [ -n "$temp_pid" ]
  then
    echo "killing $1 (pid $temp_pid)"
    kill -9 $temp_pid
  fi
}

for proc in $errant_procs
do
  kill_errant_proc $proc
done

# temp files for gathering the shmid's and semid's.  any (system wide)
# id's found will be written into these files, the id's will be
# removed, then the files themselves will be deleted.

shm_file=shm_ids.txt
sem_file=sem_ids.txt

gather_ids ()
{
  # `whoami` seems to be the best that can be done here; it grabs all
  # of my id's.  it can certainly miss other peoples remaining
  # garbage, but I don't see a good way around that.  "644" would
  # catch those id's, but what if they are in use by some other user?
  # it wouldn't be neighborly to quash them I think.  also, the
  # `system()' function didn't what I thought it should, hence,
  # writing to file and reading the id's back in and removing them
  # later.  just fyi.
  ipcs | egrep "`whoami`|shmid|semid" \
  | gawk '/shmid/ { shm = NR }
          /semid/ { sem = NR }
                  { id[NR] = $2 }
    END { for ( i = shm+1; i < sem; i++ )
            { print id[i] > "'$shm_file'";
              print "shmid " id[i];
            }
          for ( i = sem+1; i <= NR; i++ )
            { print id[i] > "'$sem_file'";
              print "semid " id[i];
            }}'
}

gather_ids

# the check for the files is the "test" for any such id's to be
# removed from the system wide resounce pool, and remove them.

if [ -e $shm_file ]
then
  temp_shm_ids=`(cat $shm_file | awk '{ print $0 }')`

  for temp_id in $temp_shm_ids
  do
    ipcrm -m $temp_id
  done
  rm $shm_file
fi

if [ -e $sem_file ]
then
  temp_sem_ids=`(cat $sem_file | awk '{ print $0 }')`

  for temp_id in $temp_sem_ids
  do
    ipcrm -s $temp_id
  done
  rm $sem_file
fi

# EOF
