#!/bin/bash
# ROX-Trasher: Trash can script
# March, 2007 - Gabriel Rojas - Fernando Garcia Bermudez

############################################################
#### Initialization

# Determine the path of the script
APPDIR=`dirname "$0"`
cd "$APPDIR"
APPDIR="`pwd`"

# Variables
datetime="`date +"%Y-%m-%dT%T"`"

##### Translations

# English (Default)
msg1="Zenity is not installed and you need a version >= 2.12.1 to be able to show dialogs on the screen."
msg2="HIDDEN-"
msg3="The trash can is already empty!"
msg4="Empty the trash can"
msg5="Delete all items in the trash can?\n\nNote: This can't be undone!!!"
msg6="The trash can is empty!"
msg7="Restore ALL items from the trash can?"
msg8="Move to the trash can"
msg9="Delete this item(s)?"
msg10="You don't have sufficient permissions to move"
msg11="to the trash can."
msg12="\n\nDo you still want to delete the item(s)?" 
msg13="The item"
msg14="is a symbolic link.\nThis will move the link to the trash can and leave the original item alone.\n\nDo you want to continue?"
msg15="There's one or more shortcuts on the desktop pointing to"
msg16="\nThis will move the original item to the trash can and remove the shortcuts from the desktop.\n\nDo you want to continue?"
msg17="There's one or more shortcuts on the panel pointing to"
msg18="\nThis will move the original item to the trash can and remove the shortcuts from the panel.\n\nDo you want to continue?"
appinfo1="Deletion"
appinfo2="Origin"
appinfo3="Type"
appinfo4="Restore"
appinfo5="Delete"

case $LANG in

    # Español
    es* )
	msg1="Zenity no está instalado y necesitará una versión >= 2.12.1 para poder mostrar los dialogos en pantalla."
	msg2="OCULTO-"
	msg3="¡El cesto de basura ya está vacio!"
	msg4="Vaciar el cesto de la basura"
	msg5="¿Eliminar todos los elementos del cesto de la basura?\n\nNota: ¡¡¡Esto no puede deshacerse!!!"
	msg6="¡El cesto de la basura está vacio!"
	msg7="¿Restaurar TODOS los elementos del cesto de basura?"
	msg8="Mover al cesto de la basura"
	msg9="¿Borrar este(os) elemento(s)?"
	msg10="No tiene los permisos suficientes para mover este elemento"
	msg11="al cesto de la basura."
	msg12="\n\n¿Todavia quiere eliminarlo(s)?" 
	msg13="El elemento"
	msg14="es un enlace simbólico.\nEsto moverá el enlace al cesto de la basura y no afectará al elemento original.\n\n¿Desea continuar?"
	msg15="Hay uno o más accesos directos en el escritorio apuntando a"
	msg16="\nEsto moverá el elemento original al cesto de la basura y borrará los accesos directos del escritorio.\n\n¿Desea continuar?"
	msg17="Hay uno o más accesos directos en el panel apuntando a"
	msg18="Esto moverá el elemento original al cesto de la basura y borrará los accesos directos del panel.\n\n¿Desea continuar?"
	appinfo1="Eliminación"
	appinfo2="Origen"
	appinfo3="Tipo"
	appinfo4="Restaurar"
	appinfo5="Borrar"
    ;;

    # Galego
    gl* )
	msg1="Zenity non está instalado e precisará unha versión >= 2.12.1 para poder amosar os dialogos en pantalla."
	msg2="AGOCHADO-"
	msg3="O cesto do lixo xa está baleiro!"
	msg4="Vaciar el cesto de basura"
	msg5="Eliminar todos os elementos do cesto do lixo?\n\nNota: Isto non pode desfacerse!!!"
	msg6="O cesto do lixo está baleiro!"
	msg7="Restaurar TODOS os elementos do cesto do lixo?"
	msg8="Mover ao cesto do lixo"
	msg9="¿Borrar este(es) elemento(s)?"
	msg10="Non ten os permisos suficientes para mover este elemento"
	msg11="ao cesto do lixo."
	msg12="\n\n Aínda quere eliminalo(s)?" 
	msg13="O elemento"
	msg14="é unha ligazón simbólica.\nIsto moverá a ligazón ao cesto do lixo e non afectará ao elemento orixinal.\n\nDesexa continuar?"
	msg15="Hay un ou máis accesos directos no escritorio apuntando a"
	msg16="\nIsto moverá o elemento orixinal ao cesto do lixo e borrará os accesos directos do escritorio.\n\nDesexa continuar?"
	msg17="Hai un ou máis accesos directos no panel apuntando a"
	msg18="Isto moverá o elemento orixinal ao cesto do lixo e borrará os accesos directos do panel.\n\nDesexa continuar?"
	appinfo1="Eliminación"
	appinfo2="Orixe"
	appinfo3="Tipo"
	appinfo4="Restaurar"
	appinfo5="Borrar"
    ;;

esac

# Check if zenity is installed
if !which zenity &> /dev/null; then
    if which xmessage &> /dev/null; then
        xmessage -buttons "Ok" -center "$msg1"
    else
        echo "$msg1"
    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"


# Set icon (Fernando)
#if test -e "$APPDIR/.DirIcon"; then
#     zenity --info --text="$msg19"
#     "$APPDIR/trash-icon" empty
#    rm "$APPDIR/.first_use"
# fi


# Set the fucking icon (Gabriel)
 stock=`ls "$interface"`
 if [ "$stock" = "" ];then
    "$APPDIR/trash-icon" empty
 else
    "$APPDIR/trash-icon" full
 fi

############################################################
#### Functions

# Find the name of the item
function notAForwardSlash {
    fSlash=/
    
    if [[ $1 != $fSlash ]]; then
        return 0
    else
        return 1
    fi
}

function processFileName {
    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
    
    # Add a suffix if the item is hidden
    FileName="${FileName/#./$msg2}"
    
    # Create directory for the trashed item.
    if test ! -e "$interface/$FileName-$$"; then
        mkdir "$interface/$FileName-$$"
    fi
}

# Move item to the trash can
function MoveToTrash {

    # BUG FIX: Set the file type before moving the item
    puretype=`rox -m "$m"`

    processFileName "$m"
    fixname=`basename "$m"`
    newfixname=${m//$fixname/''}

    # Create the info file in the info directory
    echo -e "[Trash Info]\nPath=$m\nDeletionDate=$datetime" > "$trash/info/$FileName-$$.trashinfo"

    # Move the trashed item to the files directory
    mv "$m" "$trash/files/$FileName-$$"

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

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

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


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

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

    echo -e "#!/bin/bash\ncd \"$interface/$FileName-$$\"\n./AppRun -restore\nexit" > "$APPDIR/.restore-all/restore-$FileName-$$"

    # Bestow the necessary permissions on executables
    chmod 777 "$interface/$FileName-$$/AppRun"
    chmod 777 "$APPDIR/.restore-all/restore-$FileName-$$"

    # BUG FIX: Items with spaces 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
}
# Not implemented yet
# "$APPDIR/other-trashcans" "$APPDIR" "$trash" "$interface" "$appinfo1" "$datetime" "$appinfo2" "$appinfo3" "$appinfo4" "$appinfo5"

############################################################
#### Arguments Parsing

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

    # Check trash can contents
    stuff=`ls "$interface"`

    if [ "$stuff" = "" ]; then
        zenity --window-icon="$APPDIR/.DirIcon" --error --text "$msg3"
    else
        # Ask for confirmation
        zenity --window-icon="$APPDIR/.DirIcon" --title "$msg4" --warning --text "$msg5"

        # 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

    # Check trash can contents
    stuff=`ls "$interface"`

    if [ "$stuff" = "" ]; then
        zenity --window-icon="$APPDIR/.DirIcon" --error --text "$msg6"
    else
        # Ask for confirmation
        zenity --window-icon="$APPDIR/.DirIcon"  --warning --text "$msg7"

        # 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="$msg8" --window-icon="$APPDIR/.DirIcon" --question --text "$msg9"

        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 "$msg10 $m $msg11"
                    continue
                fi

                # Check if the item can be trashed (read access).
                if [ ! -r "$m" ]; then 
                    zenity --warning --window-icon="$APPDIR/.DirIcon" --text "$msg10 $m $msg11$msg12"
                    [ $? -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 "$msg13 $m $msg14"

                    # If they chose to cancel.
                    [ $? -eq 0 ] || exit
                fi
                
                # Test to see if the item had a link to it on the pinboard.
                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"
                    if [ "$?" = "0" ]; then

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

                        # 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
                            processFileName "$m"

                            # 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

                # Test to see if the item had a link to it on the panel.
                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"
                    if [ "$?" = "0" ]; then

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

                        # 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
                            processFileName "$m"

                            # 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
