#!/bin/bash
# echo "un - extract archive in a new directory. Usage: un <archivefile>"
# (c) 198x-2004 Tero.Karvinen atSign iki.fi GNU General Public Licence
# 2004-10-26 Fix: no longer lose part of version number when removing suffix. Third less code. 
# 2003-09-09 Rewrite as original was lost. License GPL.
# 198x	First version for (Digital?) unix
# requires: perl, unpackers

### unpack and it's helper functions

unpack() # unpack archive $1 to a new directory
{	 # do not create nested dirs if archive is under single main dir
	#	P=`uncompress_prog $1`
	case "$1" in
		*.tar.gz)	S=".tar.gz";	P="tar -zxvf";;
		*.tgz)		S=".tgz"; 	P="tar -zxvf";;
		*.tar.bz2)	S=".tar.bz2";	P="tar -jxvf";; # tested
		*.tar.bzip2)	S=".tar.bzip2";	P="tar -jxvf";;
		*.zip) 		S=".zip";	P="unzip";;
		#*.rpm)		S=".rpm";  	P="rpm2cpio PROG |cpio -dvi";; # not working (yet)
		*.tar) 		S=".tar";	P="tar -xvf";;
		*.bz2) 		S=".bz2";	P="bunzip2 -d -v";; # .tar.bz2 is preferred to this
		#*.gz) P="gunzip -d -v";;
		*.arj) 		S=".arj";	P="unarj";;
		*.lha) 		S=".lha";	P="lha x";;
		*.ace) 		S=".ace";	P="unace";;
		*.rar) 		S=".rar";	P="unrar";;
		*.cab) 		S=".cab";	P="cabextract";;
		#*.cpio) P="cpio -dvi" # what is the suffix?
		*.Z) 		S=".Z";		P="uncompress";;
		*.zoo) 		S=".zoo";	P="zoo -extract";;	
		*) echo "$1 - not a known archive, skipping" ;;
	esac
	echo $1
	DIR=`echo "$1"|perl -pe "s/$S//"`;
	if [ -e $DIR ]; then
		echo "$1 - $DIR allready exists, skipping"
	else
		mkdir $DIR
		cd $DIR
		echo "### $1 - Extracting with '$P' to dir \"$DIR\""
		eval $P ../$1 |tr '\n' '   ' && echo ""
		if [[ 1 -eq "`ls|wc -l`" ]]; then 
			echo "removing unneeded nested directory"
			EXTRADIR=`ls`
			mv $EXTRADIR/* .
			rmdir $EXTRADIR
			cd ..
		fi
		echo "# $1 extracted to \"$DIR\""
		echo ""
	fi

}

### Main ###

if [ -z $1 ]; then 
	echo "un - extract archive in a new directory. Usage: un <archivefile>" 
fi

while [ ! -z "$1" ] 
do
	if [ -d "$1" ]; then 
		echo "$1 - directory, skipping"
	else
		unpack "$1"
		DONE="$DONE $1";
	fi
	shift
done
echo "### Processed: $DONE";

### (c)2003 Tero.Karvinen atSign iki.fi GNU General Public Licence
