#! /bin/sh
# courtesy of Jarek Nieplocha, to clean ipc's
# Modified by Bill Gropp to apply only to calling user
ipccmd=ipcrm
username=`whoami`
for arg in "$@" ; do
   case $arg in
	-help|-u|-us*|-h)
	echo "cleanipcs [-show] [-echo]"
	exit 1
	;;
	-echo)
	set -x
	;;
	-show)
	ipccmd="echo ipcrm"
	;;
	*)
	if [ -n "$arg" ] ; then
  	    echo "Unrecognized argument $arg"
	    exit 1
	fi
	;;
   esac
done
#
# LINUX uses an incompatible form of the ipcrm command!  Try to detect this
# An earlier version looked at the output of ipcrm, but that output
# keeps changing.  The following code from Ralf Wildenhues attempts to 
# use the Linux /proc interface instead.
#statvalue=`ipcrm 2>&1`
#if [ $? != 0 ] ; then 
#    if [ "$statvalue" = 'usage: ipcrm [shm | msg | sem] id' ] ; then
#        UseLinux=1
#    fi
#fi
#if [ $UseLinux = 0 ] ; then
if [ x`uname -s` = xLinux ] ; then
    # try to use /proc interface if possible
    # and hope it does not change too often
    if [ -r /proc/sysvipc/shm  ] ; then
    	cat /proc/sysvipc/shm \
	| gawk '{if ($8 == uid) printf("%s %s\n", comm, $2)}' uid=$UID comm="$ipccmd shm " \
	| sh > /dev/null
    else
	ipcs -m \
	| gawk '{if ($3 == name) printf("%s %s\n", comm, $2)}' name=$username comm="$ipccmd shm " \
	| sh > /dev/null
    fi
    if [ -r /proc/sysvipc/sem ] ; then
    	cat /proc/sysvipc/sem \
	| gawk '{if ($5 == uid) printf("%s %s\n", comm, $2)}' uid=$UID comm="$ipccmd sem " \
	| sh > /dev/null
    else
	ipcs -s \
	| gawk '{if ($3 == name) printf("%s %s\n", comm, $2)}' name=$username comm="$ipccmd sem " \
	| sh > /dev/null
    fi
else
    $ipccmd `ipcs | awk '{if ((($1 == "m") || ($1 == "s")) && ($5 == "'$username'")) print sprintf("-%s %s",$1,$2) }'`
fi
#
# Here is the old LINUX code
#    #
#    # For LINUX, we need this instead:
#    ipcs -m | gawk '{if ($3 == name) printf("%s %s\n", comm, $2)}' name=$username comm="$ipccmd shm " | sh > /dev/null
#    ipcs -s | gawk '{if ($3 == name) printf("%s %s\n", comm, $2)}' name=$username comm="$ipccmd sem " | sh > /dev/null
#
# mpirun could call this for systems that use SYSV shared memory features,
# just to keep them friendly.


