#!/bin/bash
#
# xe - eXtract Everything 
# Copyright (c) Markus Gaugusch <xe@gaugusch.at> 2002
#
# CVS info:
# $Author: markus $ 
# $Date: 2002/07/22 19:11:16 $ 
# $Revision: 1.4 $ 
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. 
#
# This program 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 General Public License for more details. 
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##################################################

VERSION=0.1
EXTENSIONS="tar.gz tgz tar.bz2 tb2 tbz bz2 gz zip src.rpm spm tar"
VERBOSE= # change this to "VERBOSE=-v" for more default verbosity!

function usage
{
	cat << _EOF
xe - eXtract Everything v$VERSION (c) 2002 Markus Gaugusch <xe@gaugusch.at>
Usage: xe [-d dir] [-h] [-v] file1 ... fileN
-d dir         Extract in directory "dir"
-h, --help     Show this info
-v, --verbose  Increase verbosity
_EOF
	exit -1
}

# extract - extract the file with given extension
# parameters: 
# $1: filename
# $2: extension
function extract 
{
	case "$2" in
	tar.gz|tgz)
		zcat $1 | tar $VERBOSE -xf -
		;;
	tar.bz2|tb2|tbz)
		bzcat $1 | tar $VERBOSE -xf -
		;;
	bz2)
		bunzip2 $1
		;;
	gz)
		gunzip $1
		;;
	zip)
		unzip $1
		;;
	src.rpm|spm)
		rpm -ih $VERBOSE $1
		;;
	tar)
		tar $VERBOSE -xf $1
		;;
	*)
		echo Unknown extension: $2
	esac
	if [ "$VERBOSE" ] ; then
		echo Return value: $?
	fi
}

if [ $# -lt 1 ] ; then
	usage
fi

PARAMS=`getopt -l help,verbose -o hvd -n xe -- "$@"`

while [ -n "$*" ] ; do
	case "$1" in
		-d)
			USEDIR=$2
			shift 2
			;;
		-v)
			VERBOSE=-v
			shift
			;;
		-h|--help)
			usage
			shift
			;;
		--)
			shift # skip seperator
			;;
		*)
			FILES="$FILES $1"
			shift
			;;
	esac
done

curdir="`pwd`"
for file in $FILES ; do
	if [ "$USEDIR" ] ; then
		cd "$curdir"
		path="`dirname $file`"
		cd $path
		path="`pwd`"
		file="$path/`basename $file`"
		cd "$USEDIR"
	fi
	for ext in $EXTENSIONS ; do
		if [ "${file%%$ext}" != "$file" ] ; then
			if [ "$VERBOSE" ] ; then
				echo File: $file, Ext: $ext 
			fi
			extract $file $ext
			break
		fi
	done
done
