#!/bin/bash

# prologue_local arguments
# Script is run under uid of oar who is sudo
# argv[1] is the jobid
# argv[2] is the user's name
# argv[3] is the job script name if exists

. ~oar/lock_user.sh
USERFILE="/tmp/oar_user_list.oar.$2"
USERFILETMP="$USERFILE.tmp"

LOCKRESOURCE="oarlock"
#LOCKRESOURCE=$2

lock_file $1 $LOCKRESOURCE
if (( $? == 1 ))
then
    echo "/!\\ Lock command timed out, it overrides previous command"
fi

grep -v "^$1$" $USERFILE > $USERFILETMP
NBOTHERJOBS=`grep -vc "^$1$" $USERFILE`
mv -f $USERFILETMP $USERFILE

##################################################
# EPILOGUE

echo "NBOTHERJOBS= $NBOTHERJOBS"
if (( $NBOTHERJOBS < 1 ))
then
    #look if the user is "root" or "oar" or an admin user 
    # TO CHANGE WITH A BETTER TEST !!!!!!!
    cat /etc/security/access.conf | grep -v "\#" | grep $2 > /dev/null
    if (( $? != 0 ))
    then
        # we are sure that this user $2 has no other reservation active on this node
        echo "We can frag everything owned by user $2: sudo -u $2 kill -9 -1 "
    fi
fi

ACCESS_FILE=/etc/security/access_cluster.conf

#ALLOWEDUSERS=`cat $ACCESS_FILE | grep -v "\#" | grep "^-" | sed s/\-:ALL\ EXCEPT\ // |  sed s/:ALL// | sed s/$2// | sed s/^\ *// | sed s/\ *$//`

#echo "+:ALL:LOCAL" > $ACCESS_FILE
#echo "-:ALL EXCEPT $ALLOWEDUSERS:ALL" >> $ACCESS_FILE

ACCESS_FILE_NEW=/tmp/access_cluster.conf.new

NB_SAMELINES=`grep -c "^+:${2}" < "${ACCESS_FILE}"`
(( NB_SAMELINES = NB_SAMELINES - 1 ))
grep -v "^+:${2}" < "${ACCESS_FILE}" > "${ACCESS_FILE_NEW}"
grep -m $NB_SAMELINES "^+:${2}" < "${ACCESS_FILE}" >> "${ACCESS_FILE_NEW}"
sudo mv -f "${ACCESS_FILE_NEW}" "${ACCESS_FILE}"

###################################################

unlock_file $1 $LOCKRESOURCE
if (( $? == 1 ))
then
    echo "/!\\unlock command says that it is not our lock"
fi
