#!/bin/sh
##############################################################################
# ---[ unpacker.sh ] ---
# script to look for rar files inside a specific directory. 
# if found, unrar them 
# w 10/29/08 horto
##############################################################################
DLDIR=/mnt/HD_a2/media
LOG=/mnt/HD_a2/logs/unpack.log
UNRAR=/ffp/bin/unrar

# quick and dirty check to make sure no active downloads.
# because we don't want to unrar/delete files that may be actively downloading!
if [ `/ffp/bin/transmission-remote -l | wc -l` -gt 1 ]; then
  # stop, because a download is active.
  exit 0 
  
else
  # continue; because there are no active downloads.
  # check incoming DLDIR
  for FILE in `find $DLDIR -name "*.rar"`; do
    if [ "$FILE" != "*.rar" ]; then
      # shell-fu to extract to path containing the rar
      FILENAME=`expr //$FILE : '.*/\(.*\)'`
      UNPACKDIR=`echo $FILE | sed -e s/$FILENAME//g`
      echo [`date`] Extracting "$FILE" ... >> $LOG
      
      # unrar file to the directory its sitting in
      $UNRAR x -y "$FILE" "$UNPACKDIR" >> /dev/null 2>&1
      echo [`date`]   ... done extracting. >> $LOG
      
      # cleanup - remove the rar file(s) 
      # note: match .rar, .r01, .r02 ... etc
      echo [`date`] Removing "$FILENAME and rar files." >> $LOG
      for j in `find $UNPACKDIR -name "*.r??"`; do
        rm $j
      done 
    fi
  done

  exit 0
fi

