#!/bin/bash
#
# v0.2
#
# 2004-09-23: Added support for validating DIRNAME (avizion)
#
###############################################################

# Default target - if parameter 2 is omitted.
DEFTARGET="/ad5"

# Validate this in DIRNAME (empty for anything)
VALID="incoming/dvdr"

# External binaries
LS="/bin/ls"
CP="/bin/cp"
UNRAR="/usr/local/bin/rar"
ECHO="/bin/echo"
GREP="/usr/bin/grep"
MKDIR="/bin/mkdir"
DATE="/bin/date"

###############################################################
# DON'T EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING!
###############################################################

if [ "$1" == "" ]; then
	$ECHO "Usage: $0 DIRNAME [TARGET]"
	exit 1
fi

if [ "$VALID != "" ]; then
	validate=`$ECHO -n $1|$GREP -iF "$VALID"`
	if [ "$validate" == "" ]; then
		$ECHO "Error: path $1 did not contain $VALID!"
		exit 1
	fi
fi

if [ "$2" != "" ]; then
  DEFTARGET="$2"
fi

if [ -d "$DEFTARGET" ]; then
  echo -n ""
else
  $ECHO "Error: TARGET $DEFTARGET is invalid!"
fi

cds=`$LS -1 $1|$GREP -iE "^(cd[1-9]|dis[c|k][1-9])"`
cds="$cds ."

for cdDir in $cds; do
  if [ -d "$1/$cdDir" ]; then
    firstFile=`$LS -1 $1/$cdDir|$GREP -iE "(part01|rar|001)"|head -1`
    if [ "$firstFile" != "" ]; then
      if [ -e $DEFTARGET/$1 ]; then
        $ECHO -n ""
      else
        mkDir=`$MKDIR $DEFTARGET/$1`
      fi
      copyNfo=`$CP $1/*.nfo $DEFTARGET/$1/`
      echo "Started: `$DATE`"
      echo "Unpacking $1/$cdDir/$firstFile to $DEFTARGET"
      unRar=`$UNRAR e $1/$cdDir/$firstFile $DEFTARGET/$1/`
      echo "Stopped: `$DATE`"
    fi
  fi
done

exit 0

