trash_control

#!/bin/ksh

#Permet de gérer une corbeille dans un shell.
#Les fichiers ou répertoires sont compressés.
#La version actuelle fonctionnera incorrectement
#si des fichiers ou répertoires du même nom sont supprimés.

TRASH=~/.MyTrash


delete()
{
  if ! ([ -f $1 ] || [ -d $1 ])
  then
    echo "$1 not found"
    return
  fi
  if ! [ -w $1 ]
  then
    echo "You can not delete $1"
    return
  fi
  del_file=`basename $1`
  trash_file=$del_file.trash
  trash_oldpos=`dirname $1`
  mv $1 $TRASH
  if ! expr $trash_oldpos : "^/" >/dev/null 2>&1
  then
    trash_oldpos=`pwd`/$trash_oldpos
  fi
  echo $trash_oldpos > $TRASH/$trash_file
  tar -cf $TRASH/$del_file.tar $TRASH/$del_file
  gzip $TRASH/$del_file.tar
  rm -rf $TRASH/$del_file
}

undelete()
{
  trash_file=`basename $1`.trash
  if ! [ -f $TRASH/$trash_file ]
  then
    echo "$1 not found in trash"
    return
  fi
  trash_oldpos=`cat $TRASH/$trash_file`
  cd $TRASH
  gunzip $TRASH/$1.tar.gz
  tar -xf $TRASH/$1.tar
  mv $TRASH/$1 $trash_oldpos
  rm $TRASH/$trash_file
  rm $TRASH/$1.tar
  cd - >/dev/null
}

empty()
{
  rm -rf $TRASH/*
}

display()
{
  tgz_file_list=`ls $TRASH | grep -v "trash$"`
  if [ -z "$tgz_file_list" ]
  then
    echo "Trash empty"
    return
  fi
  for tgz_file in $tgz_file_list
  do
    file=`expr $tgz_file : "\(.*\)[.]tar[.]gz$"`
    trash_file=$file.trash
    trash_oldpos=`cat $TRASH/$trash_file`
# echo "$\033[5;1H\cfile\033[5;18H\cFrom: $trash_oldpos"
    echo "$file\t\tFrom: $trash_oldpos"
  done
}

if ! [ -d $TRASH ]
then
  if ! mkdir $TRASH
  then
    echo "Error creating trash directory: $TRASH"
  fi
fi

case $1 in
  del)
       shift
       for i in $*
       do
delete $i
       done
       ;;
  undel)
       shift
       for i in $*
       do
undelete $i
       done
       ;;
  empty)
       empty
       ;;
  list)
       display
       ;;
esac