#!/bin/sh
# Nico Schottelius
# sort files by type and delete binaries
# 17-Jan-2004
# I used this script to sort my backup
#
# syntax:
# find $dir -exec $thisscript $outputdir {} \;
#
# example:
# find ~/backup -exec sort-backup.dothejob ~/sorted {} \;
#

DIR="$1"
FILE="$2"
TYPE=`file "$FILE" | sed 's/.*://'`
RM="rm -f"
MV="mv -i"
MKDIR="mkdir -p"

case "$TYPE" in
   " ELF 32-bit LSB"*)
      echo "Removing $FILE"
      $RM -f "$FILE"
      exit 0
      ;;
   *"image data"*)
      echo "Moving $FILE to images"
      TARGETDIR="$DIR/images"
      ;;
   *MPEG*)
      echo "Moving $FILE to sorted/video"
      TARGETDIR="$DIR/video"
      ;;
    *"MP3"*|*"libVorbis"*)
      echo "Moving $FILE to audio"
      TARGETDIR="$DIR/msdoc"
      ;;
   *Microsoft*)
      echo "Moving $FILE to msdoc"
      TARGETDIR="$DIR/msdoc"
      ;;
   *"gzip compressed data"*|*"Zip archive data"*)
      echo "Moving $FILE to archives"
      TARGETDIR="$DIR/archives"
      ;;
   *"mail text"*)
      echo "Moving $FILE to mails"
      TARGETDIR="$DIR/mails"
      ;;
   " data")
      echo "Moving $FILE to data"
      TARGETDIR="$DIR/data"
      ;;
   *)
      echo "Do nothing with $FILE ($TYPE )"
      exit 0
      ;;
esac

if [ ! -e "$TARGETDIR" ]; then
   echo "Creating $TARGETDIR"
   $MKDIR "$TARGETDIR"
fi
if [ ! -d "$TARGETDIR" ]; then
   echo "Don\'t fool me, I assumed "$TARGETDIR" is a directory."
   exit 1
else
   if [ -e "$TARGETDIR"/"`basename "$FILE"`" ]; then
      DATE=`date +%s`
      echo file already exists, renaming to $FILE.$DATE
      $MV "$FILE" "$TARGETDIR"/`basename "$FILE"`.$DATE
   else
      echo "$TARGETDIR"/`basename "$FILE"`
      $MV "$FILE" "$TARGETDIR"
   fi
fi