#! /bin/sh
# Trashcan by Dennis Tomas

export TEXTDOMAIN="TrashCan"
export TEXTDOMAINDIR="./locale" 

APPDIR=`dirname "$0"`
cd -P "$APPDIR"
APPDIR="`pwd`"

ROX=rox


if [ -z "$XDG_DATA_HOME" ]; then
  XDG_DATA_HOME="${HOME}/.local/share"
fi
[ -d "$XDG_DATA_HOME/Trash/files" ] || mkdir -p "${HOME}/.local/share/Trash/files"
[ -d "$XDG_DATA_HOME/Trash/info" ] || mkdir -p "${HOME}/.local/share/Trash/info"
XDG_TRASHDIR="$XDG_DATA_HOME/Trash"

if [ -z "$XDG_CONFIG_HOME" ]; then
  XDG_CONFIG_HOME="${HOME}/.config"
fi
CONFDIR="$XDG_CONFIG_HOME/rox4debian.berlios.de/Trashcan"
echo "$APPDIR" > "$CONFDIR/appdir"
# used by 0install-wrappers to set the path of the wrapper
if [ -f "$CONFDIR/wrapper" ]; then
  WRAPPER=`cat "$CONFDIR/wrapper"`
else
  unset WRAPPER
fi
TRASHDIR="$CONFDIR/Trash"

export APPDIR WRAPPER XDG_DATA_HOME XDG_CONFIG_HOME ROX CONFDIR XDG_TRASHDIR TRASHDIR

if [ ! -d "$TRASHDIR" ]; then
  mkdir -p "$TRASHDIR"
fi

if [ -z "$1" ]; then
  $ROX -d "$TRASHDIR"
  if [ -n "`ls \"$XDG_TRASHDIR/files\" 2> /dev/null`" ]; then  
    # import existing trash
    for trashfile in ${XDG_TRASHDIR}/files/*
    do
      "$APPDIR/import-trash.sh" "$trashfile"
    done
  fi
  if [ -n "`ls \"$TRASHDIR\" 2> /dev/null`" ]; then
    # remove wrappers for files removed or restored by other trashcans
    for wrapper in ${TRASHDIR}/*
    do
      trashfilename=`basename "$wrapper"`
      if [ ! -f "$XDG_TRASHDIR/info/$trashfilename.trashinfo" ]; then
        chmod +w "$TRASHDIR"
        chmod -R +w "$wrapper" 
        rm -rf "$wrapper"
        chmod -w "$TRASHDIR"
      fi
    done
  fi
  "$APPDIR/update-icon.sh"
  exit 0
fi


case $1 in
  --empty)
    if [ -z "`ls $XDG_TRASHDIR/files 2> /dev/null`" ]; then
      "$APPDIR/dialog.py" i "`gettext \"The Trashcan is already empty.\"`"
      exit 1
    fi
    "$APPDIR/dialog.py" q "`gettext \"Delete all files in Trashcan? (This can't be undone!)\"`" || exit 1
    trashfiles=`echo $XDG_TRASHDIR/files/* | sed -e 's/\ \//\:/g'`
    IFS=":"
    for trashfile in $trashfiles
    do
      "$APPDIR/take-out.sh" Remove "$trashfile" -y
    done
    ;;
  --restore-all)
    if [ -z "`ls $XDG_TRASHDIR/files 2> /dev/null`" ]; then
      "$APPDIR/dialog.py" i "`gettext \"The Trashcan is empty.\"`"
      exit 1
    fi
    "$APPDIR/dialog.py" q "`gettext \"Restore all files in Trashcan?\"`" || exit 1
    for trashfile in $XDG_TRASHDIR/files/*
    do
      "$APPDIR/take-out.sh" Restore "$trashfile" -y
    done
    ;;
  --restore)
    trashfile="$2"
    "$APPDIR/take-out.sh" Restore "$trashfile"
    ;;
  --delete)
    trashfile="$2"
    "$APPDIR/take-out.sh" Remove "$trashfile"
    ;;
  *)
    # ask if they should be trashed away
    trashfiles=`echo "$@" | sed -e 's/\ \//\:\//g'`
    "$APPDIR/dialog.py" q "`gettext \"Put file(s) into Trashcan?\"` `echo :$trashfiles | sed -e 's/\:/\n/g'`" || exit 1
    IFS=":"
    for trashfile in $trashfiles
    do
      "$APPDIR/trash-away.sh" "$trashfile"
    done
    ;;
esac

exit 0
