#!/bin/ksh
# @(#) untar.ksh 1.0 93/11/10
# 92/10/08 john h. dubois iii (john@armory.com)
# 92/10/31 make it actually work if archive isn't in current dir!
# 93/11/10 Added pack and gzip archive support

if [ $# -eq 0 ]; then
    echo \
"$0: extract tar archives into directories, uncompressing if neccessary.
Usage: $0 archive[.tar[.[Z|gz]]] ..
If an archive name given does not end in .tar, .tar.Z, or .tar.gz, it is
searched for first with .tar added, then .tar.Z, and then .tar.gz added. 
The real filename must end in either .tar, .tar.Z, or .tar.gz.  A
directory with the name of the archive is created in the current directory
(not necessarily the directory that the archive is in) if it does not
exist, and the the contents of the archive are extracted into it. 
Absolute pathnames in tarfiles are suppressed."
    exit
fi

OWD=$PWD

for file; do
    cd $OWD
    if [[ "$file" = *.tar*(.@(z|Z|gz)) ]]; then
	ArchiveName=${file%%.tar*(.@(z|Z|gz))}
    else
        ArchiveName=$file
	for ext in "" .Z .z .gz; do
	    if [ -f "$file.tar$ext" ]; then
		file="$file.tar$ext"
		break
	    fi
	done
	if [ ! -f "$file" ]; then
	    print -u2 "$file: cannot find archive."
	    continue
	fi
    fi
    if [ ! -r "$file" ]; then
	print -u2 "$file: cannot read."
	continue
    fi
    DirName=${ArchiveName##*/}
    if [ -d "$DirName" ] || mkdir "$DirName"; then :; else
	print -u2 "$DirName: could not make archive directory."
	continue
    fi
    cd $DirName
    [[ "$file" != /* ]] && file=$OWD/$file
    print "Extracting archive $file into directory $DirName..."
    case "$file" in
    *.tar.Z) zcat $file | tar xvAf -;;
    *.tar.z) pcat $file | tar xvAf -;;
    *.tar.gz) gzcat $file | tar xvAf -;;
    *.tar) tar nxvAf $file;;
    esac
    print "Done extracting archive $file into directory $DirName."
done
