#!/bin/sh
#
# unrarToDir v0.1.0 : unrar archives to an unique directory
#
#
#
# Copyright (C) 2006 Laurent Marsac
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
#
#
#
# You can concact me at : laurent DOT marsac AT laposte DOT net
#
#
#
# Usage : unrarToDir rarfile <unrar options>
# tested with : UNRAR 3.40 beta 4 freeware
# also needs : sed sort uniq wc

# some settings
MAXNAMETEST=99
NAMETEST=""

function usage {
	echo "Usage: $0 rarfile <unrar opts>"
}


# check our command line
if [ "a"$1 = "a" ]; then
	usage
	exit 1
fi


ls $1 > /dev/null 2>&1
if [ $? != 0 ]; then
	echo "file \'$1\' not found"
	usage
	exit 1
fi


# save filename
FILENAME=$1

# shift for launching unrar
shift 1

# test if archive is safely extracting in one dir 
unrar vb $FILENAME > /dev/null 2>&1
if [ $? != 0 ]; then
	echo "unrar error detected..."
	unrar vb $FILENAME
	exit $?
else
	DIRTEST=`unrar vb $FILENAME | sed -e 's,\/.*,,' | sort | uniq | wc -l`
	if [ $DIRTEST = "1" ]; then
		echo "extracting $FILENAME in the normal way..."
		unrar $@ $FILENAME
		exit $?
	fi
fi

# if not, look for a directory to export and unrar
PREFIXNAME=`echo $FILENAME | sed -e 's,\.[^\.]*$,,'`

while [ "$NAMETEST" != "$MAXNAMETEST" ]; do
	ls $PREFIXNAME$NAMETEST > /dev/null 2>&1
	if [ $? == 0  ]; then
		echo "$PREFIXNAME$NAMETEST exists"
		NAMETEST=`echo $(($NAMETEST+1))`
	else
		echo "$PREFIXNAME$NAMETEST dont exists, extracting $FILENAME to it:"
		unrar $@ $FILENAME "$PREFIXNAME$NAMETEST/" 
		exit $?
	fi
done
