#!/bin/sh

# renicename - Modifie la priorit de la tche correspondant au nom spcifi.

user=""; tty=""; showpid=0; niceval="+1"         # initialisation

while getopts "n:u:t:p" opt; do
  case $opt in
   n ) niceval="$OPTARG";               ;;
   u ) if [ ! -z "$tty" ] ; then
         echo "$0: erreur: -u et -t sont mutuellement exclusives." >&2
         exit 1
       fi
       user=$OPTARG                     ;;
   t ) if [ ! -z "$user" ] ; then
         echo "$0: erreur: -u et -t sont mutuellement exclusives." >&2
         exit 1
       fi
       tty=$OPTARG                      ;;
   p ) showpid=1;                       ;;
   ? ) echo "Syntaxe: $0 [-n valeur_nice] [-u utilisateur|-t tty] [-p] motif" >&2
       echo "La modification par dfaut valeur_nice est $niceval (un nombre" >&2 
       echo "grand correspond  une priorit moins leve, mais seul root" >&2
       echo "peut descendre sous 0)" >&2
       exit 1
  esac
done
shift $(($OPTIND - 1)) # on mange tous les arguments reconnus

if [ $# -eq 0 ] ; then
  echo "Syntaxe: $0 [-n valeur_nice] [-u utilisateur|-t tty] [-p] motif" >&2
  exit 1
fi

if [ ! -z "$tty" ] ; then
  pid=$(ps cu -t $tty | awk "/ $1/ { print \\$2 }")
elif [ ! -z "$user" ] ; then
  pid=$(ps cu -U $user | awk "/ $1/ { print \\$2 }")
else
  pid=$(ps cu -U ${USER:-LOGNAME} | awk "/ $1/ { print \$2 }")
fi

if [ -z "$pid" ] ; then
  echo "$0: aucun processus ne correspond au motif $1" >&2 ; exit 1
elif [ ! -z "$(echo $pid | grep ' ')" ] ; then
  echo "$0: plusieurs processus correspondent au motif ${1}:" 
  if [ ! -z "$tty" ] ; then
    runme="ps cu -t $tty"
  elif [ ! -z "$user" ] ; then
    runme="ps cu -U $user"
  else
    runme="ps cu -U ${USER:-LOGNAME}"
  fi
  eval $runme | \
      awk "/ $1/ { printf \"  utilisateur %-8.8s  pid %-6.6s  tche %s\n\", \
      \$1,\$2,\$11 }"
  echo "Utilisez -u utilisateur ou -t tty pour restreindre vos critres de slection."
elif [ $showpid -eq 1 ] ; then
  echo $pid
else
  # On est prt; allons-y!
  echo -n "Changement de priorit pour le processus "
  echo -n $(ps cp $pid | sed 's/ [ ]*/ /g' | tail -1 |  cut -d\  -f5-)
  echo " ($pid)"
  renice $niceval $pid
fi

exit 0
