#!/bin/sh
#
# tarToDir v0.1.0 : untar 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 : tarToDir tarfile <tar options>
# tested with : tar (GNU tar) 1.14
# also needs : awk sed sort uniq wc bzip2 compress gzip

# some settings
MAXNAMETEST=99
NAMETEST=""
TESTCMD="tar"
COMPRESS_OPT=""
DIR_OPT="-C"
TESTOPTS="tvf"

function usage {
	echo "Usage: $0 tarfile <tar options>"
}


# 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 unzip
shift 1

# test if archive is compressed
# tar
$TESTCMD $TESTOPTS $FILENAME > /dev/null 2>&1
if [ $? = 0 ]; then
	COMPRESS_OPT=""
else

	# bzip2
	$TESTCMD "j"$TESTOPTS $FILENAME > /dev/null 2>&1
	if [ $? = 0 ]; then
		COMPRESS_OPT="j"
	else

		# gzip
		$TESTCMD "z"$TESTOPTS $FILENAME > /dev/null 2>&1
		if [ $? = 0 ]; then
			COMPRESS_OPT="z"
		else

			# compress
			$TESTCMD "Z"$TESTOPTS $FILENAME > /dev/null 2>&1
			if [ $? = 0 ]; then
				COMPRESS_OPT="Z"
			else
				echo "Unknown file format, exiting"
				exit 1
			fi
		fi
	fi
fi


DIRTEST=`$TESTCMD $COMPRESS_OPT$TESTOPTS $FILENAME | awk '{print $6}' | sed -e 's,\/.*,,' | sort | uniq | wc -l`
if [ $DIRTEST = "1" ]; then
	echo "extracting $FILENAME in the normal way..."
	$TESTCMD $@ $FILENAME
	exit $?
fi


# if not, look for a directory to export and untar
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:"
		mkdir "$PREFIXNAME$NAMETEST"
		$TESTCMD $@ $FILENAME $DIR_OPT "$PREFIXNAME$NAMETEST"
		exit $?
	fi
done
