#!/bin/sh


myname=`basename $0`;
LOCKFILE=/tmp/lock.$myname;
MY_USER=$USER
CMD=$*

if [ $# -eq 0 ]
then
    echo "Usage: sipalglock [ \"cmd\" | help | print | clean ]"
    echo ""
    echo "This wrapper tool is used to get SIP debug data from the kernel "
    echo "loadable module in a safe way. It creates a lock file in"
    echo "$LOCKFILE to force exclusive access to a single"
    echo "user at a time."
    echo ""
    echo "Parameters:"
    echo ""
    echo "   \"cmd\": SIP debug command to execute."
    echo "          For example: sipalglock \"cat /proc/dsc/alg/sip\""
    echo ""
    echo "   help:  print this help text"
    echo ""
    echo "   print: display the current PID in lock file"
    echo ""
    echo "   clean: delete the lock file"
    exit
fi  

if [ "$1" = "help" ]
then
    echo "Usage: sipalglock [ \"cmd\" | help | print | clean ]"
    echo ""
    echo "This wrapper tool is used to get SIP debug data from the kernel "
    echo "loadable module in a safe way. It creates a lock file in"
    echo "$LOCKFILE to force exclusive access to a single"
    echo "user at a time."
    echo ""
    echo "Parameters:"
    echo ""
    echo "   \"cmd\": SIP debug command to execute."
    echo "          For example: sipalglock \"cat /proc/dsc/alg/sip\""
    echo ""
    echo "   help:  print this help text"
    echo ""
    echo "   print: display the current PID in lock file"
    echo ""
    echo "   clean: delete the lock file"
    exit
fi  

if [ "$1" = "clean" ]
then
    rm -f $LOCKFILE 
    exit
fi

if [ "$1" = "print" ]
then
    ls -la $LOCKFILE
    echo PID: `cat $LOCKFILE`
    exit
fi



if [ $USER = root ]
then

MY_USER=mtc

fi


su -s /bin/sh    -c "


      until(umask 222; echo $$ >$LOCKFILE) 2>/dev/null
      do

      ls -l  $LOCKFILE  |gawk  '{ printf(\"User %s working from:  %s %s %s \n\",\$3,\$6,\$7,\$8)}' 
      echo PID: ${titi2=`cat $LOCKFILE`}      

      sleep 5
        
      done

      echo Lock path : $LOCKFILE
      echo \"##################sipalglock:Enter critical region###########\" 
      echo
      
      $CMD
      

      rm -f $LOCKFILE
      

     echo 
     echo 
     echo \"########sipalglock:Exit critical region#############\"


     " $MY_USER


