#!/bin/bash
# March, 2007 - Gabriel Rojas - Fernando Garcia Bermudez

# Determine the path to this application.
APPDIR=`dirname "$0"`
cd "$APPDIR"
APPDIR="`pwd`"
actual=`date +"%Y-%m-%dT%T"`

#################################################
#################################################
#	TRANSLATIONS
		###### Default = English #####
		txt1="Zenity is not installed, you need zenity >= 2.12.1"
		txt2="HIDDEN-"
		txt3="The trash is already empty!"
                txt4="Empty the Trash"
                txt5="Delete all files in trash?
(This can be undone!!!)"
                txt6="The trash is empty!"
                txt7="Restore ALL items in trash?"
                txt8="Move to trash"
                txt9="Delete this item(s)?"
                txt10="You can't move"
                txt11="to the Trash because of insufficient permissions."
                txt12="Do you still want to delete it?" 
                txt13="The item"
                txt14="is a Symbolic Link.
This will move the Symbolic Link to the Trash and leave the original item  alone.
Do you want to continue?"
                txt15="There is one or more Desktop shortcuts pointing to"
                txt16="This will move the original item to the Trash and remove the shortcut(s) from the Desktop.
Do you want to continue?"
                txt17="There is one or more Panel shortcuts pointing to"
                txt18="This will move the original item to the Trash and remove the shortcut(s) from the Panel.
Do you want to continue?"
txt19="ROX-Trasher 0.5
Fernando Garcia Bermudez - Gabriel Rojas"
                appinfo1="Deleted on:"
                appinfo2="Origin:"
                appinfo3="Type"
                appinfo4="Deleted"
                appinfo5="Origin"
                appinfo6="Restore"
                appinfo7="Delete"

	case $LANG in
		######## Español ########
		es* )
                    # AppRun strings
		txt1="Zenity no está instalado, necesita >= 2.12.1"
		txt2="OCULTO-"
		txt3="¡La papelera ya esta vacia!"
                txt4="Vaciar la papelera"
                txt5="¿Eliminar todos los elementos de la papelera?
(¡¡¡Esto no puede deshacerse!!!)"
                txt6="¡La papelera esta vacia!"
                txt7="¿Restaurar TODOS los elementos de la papelera?"
                txt8="Mover a la papelera"
                txt9="¿Borrar este/os elemento(s)?"
                txt10="No puedes mover este elemento"
                txt11="a la papelera por no tener permisos suficientes."
                txt12="¿Todavia quiere eliminarlo(s)?" 
                txt13="El elemento"
                txt14="es un enlace simbolico.
La papelera moverá el enlace y dejará el elemento.
¿Deseas continuar?"
                txt15="Hay uno o mas accesos de escritorio apuntando a"
                txt16="La papelera moverá el elemento y el acceso del tablero.
¿Deseas continuar?"
                txt17="Hay uno o mas accesos de panel apuntando a"
                txt18="La papelera moverá el elemento y el acceso del panel.
¿Deseas continuar?"
                txt19="ROX-Trasher 0.5 
Fernando Garcia Bermudez - Gabriel Rojas"
                appinfo1="Borrado el:"
                appinfo2="Origen:"
                appinfo3="Tipo"
                appinfo4="Eliminación"
                appinfo5="Origen"
                appinfo6="Restaurar"
                appinfo7="Borrar"
		;;
		######## Galego ########
		gl* )
                    # AppRun strings
		txt1="Zenity non está instalado, precisa de >= 2.12.1"
		txt2="AGOCHADO-"
		txt3="O cesto do lixo xa está baleira"
                txt4="Baleirar o cesto do lixo"
                txt5="Eliminar todos os elementos do cesto do lixo?
(Isto non pode desfacerse!!!)"
                txt6="O cesto do lixoxa está baleiro!"
                txt7="Restaurar TODOS os elementos do cesto do lixo?"
                txt8="Mover ao cesto do lixo"
                txt9="¿Borrar este(os)/os elemento(s)?"
                txt10="Non podes mover este elemento"
                txt11="ao cesto do lixo por non tener permisos dabondos."
                txt12="Aínda quere eliminalo(s)?" 
                txt13="O elemento"
                txt14="é unha ligazón simbólica.
O cesto do lixo moverá a ligazón e deixará o elemento.
Desexa continuar?"
                txt15="Hai un ou máis accesos de escritorio apuntando a"
                txt16="O cesto do lixo moverá o elemento e o acceso do taboleiro.
Desexa continuar?"
                txt17="Hai un ou máis accesos do panel apuntando a"
                txt18="O cesto do lixo moverá o elemento e o acceso do panel.
Desexa continuar?"
                txt19="ROX-Trasher 0.5 
Fernando Garcia Bermudez - Gabriel Rojas"
                appinfo1="Borrado o:"
                appinfo2="Orixe:"
                appinfo3="Tipo"
                appinfo4="Eliminación"
                appinfo5="Orixe"
                appinfo6="Restaurar"
                appinfo7="Borrar"
		;;

	esac

### End of Translations ###
###########################
###########################

# Check if zenity is installed.
if !which zenity &> /dev/null; then
if which xmessage &> /dev/null; then
xmessage -buttons "Ok" -center "$txt1"
else
echo "$txt1"
fi
exit
fi

# Create the Trash directory if it doesn't already exist.
if  [ "$XDG_DATA_HOME" != "" ]; then
    trash=$XDG_DATA_HOME/Trash
else
    trash=$HOME/.local/share/Trash
fi

[ -d $trash/files ] || mkdir -p $trash/files
[ -d $trash/info ] || mkdir -p $trash/info

# Create the Trash interface if it doesn't already exist
if  [ "$XDG_CONFIG_HOME" != "" ]; then
    interface=$XDG_CONFIG_HOME/ROX-Trasher
else
    interface=$HOME/.config/ROX-Trasher
fi

[ -d $interface ] || mkdir -p $interface

if test -e "$APPDIR/.first_time"; then
zenity --info --text="$txt19"
"$APPDIR/trash-icon" empty
rm "$APPDIR/.first_time"
fi

# Find the name of the file.
function notAForwardSlash
{
fSlash=/
 if [[ $1 != $fSlash ]]

  then
   return 0
  else
   return 1
 fi
}

function getFileName
{
 STRING=$1

 LENGTH=${#STRING}

 for ((n=0;n <= $LENGTH; n++))
  do
   CHAR=${STRING:$n:1}

   if notAForwardSlash $CHAR
    then
    FileName=$FileName$CHAR

   else
    FileName=""
  fi
done
}

function MoveToTrash
{
getFileName "$m"


# Add a suffix if the item is a hidden file/directory
FileName=${FileName/#./$txt2}



# Create directories for the trashed item.

# First, check if File dir exists
if test ! -e "$interface/$FileName-$$" ; then
mkdir "$interface/$FileName-$$"
fi


# Create the info file
echo "[Trash Info]
Path=$m
DeletionDate=$actual" > "$trash/info/$FileName-$$.trashinfo"


# move the item to the files Trash directory.
mv "$m" "$trash/files/$FileName-$$"

# Set the item type
  if [ -x "$trash/files/$FileName-$$/AppRun" ]; then
    filetype="rox-application"
  else
filetype=`rox -m "$trash/files/$FileName-$$"`
filetype=${filetype/\//_}
fi

# Create the item icon
"$APPDIR/item-icon" "$interface" "$FileName-$$" "$filetype" "$trash"

# Create the AppInfo file
filetype=${filetype/_/-}
echo "<?xml version=\"1.0\"?>
<AppInfo>
  <Summary>$filetype - $appinfo1 $actual - $appinfo2 $m</Summary>
  <About>
    <$appinfo3>$filetype</$appinfo3>
    <$appinfo4>$actual</$appinfo4>
    <$appinfo5>$m</$appinfo5>
  </About>
   <AppMenu>
    <Item label=\"$appinfo6\" option=\"-restore\"/>
    <Item label=\"$appinfo7\" option=\"-delete\"/>
   </AppMenu>
</AppInfo>" > "$interface/$FileName-$$/AppInfo.xml"


# Write the new AppRun file with some variables
gawk -v var="PATH" -v name="$m" -v trash="$APPDIR" -v xdg="$trash" -v store="$interface" -v file="$FileName-$$"   '{sub(var, name)}
{sub("TRASH", trash)}
{sub("XDG", xdg)}
{sub("STORE", store)}
{sub("FILE", file)}
{sub("TRASH", trash); print}' "$APPDIR/item-template" > "$interface/$FileName-$$/AppRun"

# Write the restore-all info
if test ! -e "$APPDIR/.restore-all" ; then
mkdir "$APPDIR/.restore-all"
fi

echo "#!/bin/bash
cd \"$interface/$FileName-$$\" 
./AppRun -restore
exit " > "$APPDIR/.restore-all/restore-$FileName-$$"

# Make it executables
chmod 777 "$interface/$FileName-$$/AppRun"
chmod 777 "$APPDIR/.restore-all/restore-$FileName-$$"

# BUG FIX: Item with space on their names
FileName2=${FileName//' '/%}

if [ "$FileName" != "$FileName2" ]; then 
mv "$APPDIR/.restore-all/restore-$FileName-$$" "$APPDIR/.restore-all/restore-$FileName2-$$"
fi

}

function RemoveOldRoxIcon
{
if test -e $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default; then
while grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default
 do


  number=`grep -m 1 ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default`

  # Write the new Pinboard file with the trashed item removed.
  gawk -v var="$number" '{sub(var, ""); print}' $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default > $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default1

  # Rename the new pb_Default file
  mv $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default1 $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default

  # Restart the pinboard.
  rox -S

done
fi
}

function RemoveOldRoxIcon_Panel
{
if test -e $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default; then
while grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default
 do


  number=`grep -m 1 ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default`

  # Write the new Panel file with the trashed item removed.
  gawk -v var="$number" '{sub(var, ""); print}' $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default > $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default1

  # Rename the new pan_Default file
  mv $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default1 $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default

  # Restart the panel.
  rox -S

done
fi
}

if [ "$1" = "-empty" ]
then

 # See what is in the trash.
 stuff=`ls $interface`

if [ "$stuff" = "" ]; then
zenity --window-icon="$APPDIR/.DirIcon" --error --text "$txt3"
else
 # Write the confirmation message.
zenity --window-icon="$APPDIR/.DirIcon"  --title "$txt4" --warning --text "$txt5"

  # If they chose to cancel.
  [ $? -eq 0 ] || exit

  # If they chose to delete.
  rm -fr "$interface/"*
  rm -fr "$APPDIR/.restore-all/"*
  rm -fr "$trash/files/"*
  rm -fr "$trash/info/"*

 "$APPDIR/trash-icon" empty


fi
elif [ "$1" = "-restore-all" ]
then

 # See what is in the trash.
 stuff=`ls $interface`

if [ "$stuff" = "" ]; then
zenity --window-icon="$APPDIR/.DirIcon" --error --text "$txt6"
else

zenity --window-icon="$APPDIR/.DirIcon"  --warning --text "$txt7"

  # If they chose to cancel.
  [ $? -eq 0 ] || exit


cd "$APPDIR/.restore-all"
    for restore in `ls`; do
            `./$restore`
        done


fi


else

 # Check to see if they clicked on the application or sent a file or directory to be deleted.
 if [ "$*" = "" ]
 then

  # If they just clicked on the icon.
  exec rox $interface

else


 # If they sent something to the trash can.
zenity --title="$txt8" --window-icon="$APPDIR/.DirIcon" --question --text "$txt9"
if [ "$?" = "0" ]
 then

 for m in "$@"
 do

            # Check if the item can be deleted (write access).
            if [ ! -w "$m" ]; then 
                zenity --error --window-icon="$APPDIR/.DirIcon" --text "$txt10 $m $txt11"
                continue
            fi
            
            # Check if the item can be trashed (read access).
            if [ ! -r "$m" ]; then 
                zenity --warning --window-icon="$APPDIR/.DirIcon" --text "$txt10 $m $txt11 
$txt12"
                [ $? -eq 0 ] || continue
            fi

  # Test to see if the item is a symbolic link.
  if [ -h "$m" ]
  then

   # Write the confirmation message.
zenity --window-icon="$APPDIR/.DirIcon" --warning --text "$txt13 $m $txt14"

  # If they chose to cancel.
  [ $? -eq 0 ] || exit

 fi
if test -e $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default; then
 match=`grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default`

 # Test $match to see if the item had a link to it on the pinboard.
 test "$match"
 if [ "$?" = "0" ]
 then

  # Write the confirmation message.
zenity --window-icon="$APPDIR/.DirIcon" --warning --text "$txt15 $m
$txt16"

  # If they chose to cancel.
  [ $? -eq 0 ] || exit


 while check=`grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default`
 do

  OldNumber=`grep -c ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default`


# Get the filename again
getFileName "$m"


# Add a suffix if the item is a hidden file/directory
FileName=${FileName/#./$txt2}

# Create directories for the trashed item.
if test ! -e $interface/$FileName-$$; then
mkdir "$interface/$FileName-$$"
fi

# Create the shortcut file info
echo "$match" > "$interface/$FileName-$$/shortcut"

rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <PinboardRemove>
   <Path>$m</Path>
  </PinboardRemove>
 </env:Body>
</env:Envelope>
EOF

# Check to see if the entry was removed.
NewNumber=`grep -c ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pb_Default`
if [ "$OldNumber" = "$NewNumber" ]
then

# If SOAP did not work then remove the icon manualy.
RemoveOldRoxIcon "$match"

fi
done
fi

fi

if test -e $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default; then
 match_panel=`grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default`

 # Test $match_panel to see if the item had a link to it on the panel.
 test "$match_panel"
 if [ "$?" = "0" ]
 then

  # Write the confirmation message.
zenity --window-icon="$APPDIR/.DirIcon" --warning --text "$txt17 $m
$txt18"

  # If they chose to cancel.
  [ $? -eq 0 ] || exit


 while check=`grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default`
 do

  OldNumber_Panel=`grep -c ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default`


# Get the filename again
getFileName "$m"


# Add a suffix if the item is a hidden file/directory
FileName=${FileName/#./$txt2}

# Create directories for the trashed item.
if test ! -e "$interface/$FileName-$$"; then
mkdir "$interface/$FileName-$$"
fi

# Create the shortcut file info
side=`grep "panel side" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default | sed -e s/'<panel side='// -e s/'"'// -e s/'">'//`
side=`expr "$side" : '[[:space:]]*\(.*\)[[:space:]]*$'`
echo "$side" > "$interface/$FileName-$$/shortcut_panel"
label=`grep ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default | sed -e s/'<icon label='// -e s/'"'// -e s/'">'// -e s^"$m"^^ -e s/'<\/icon>'//`
label=`expr "$label" : '[[:space:]]*\(.*\)[[:space:]]*$'`
echo "$label" >> "$interface/$FileName-$$/shortcut_panel"

rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <PanelRemove>
<Side>$side</Side>
   <Path>$m</Path>
  </PanelRemove>
 </env:Body>
</env:Envelope>
EOF

# Check to see if the entry was removed.
NewNumber_Panel=`grep -c ">$m<" $HOME/.config/rox.sourceforge.net/ROX-Filer/pan_Default`
if [ "$OldNumber_Panel" = "$NewNumber_Panel" ]
then

# If SOAP did not work then remove the icon manualy.
RemoveOldRoxIcon_Panel "$match_panel"

fi
done
fi
fi

MoveToTrash "$m"


"$APPDIR/trash-icon" full
done
fi
fi
fi
