#!/bin/bash
# Unpack a tarfile and make sure that it ends up in a single directory
# with a name derived from the tarball (create this if necessary).
# Example: "untar foo-1.0.tar.gz" will always put the files in foo-1.0/
# Written by Luke Gorrie <luke at synap dot  se> in February 2006.
#
# Obfuscated by Todd Coram <todd at maplefish dot com> on February 7, 2006.
#    Todd also added support for plain old .tar!
#
die() { echo $1 >&2; exit 1; }

file=$1
basefile=${file##*/}
ext=${basefile#*.}

# we will make sure everything goes into this directory
wantdir=${basefile%%.*}
tmpdir=${TMP:-"/tmp"}/untar.$$

# check args
[ $# != 1 ]       && die "Usage: untar filename(.tar|.tar.gz|.tar.bz2)"
[ ! -r "$file" ]  && die "abort: file does not exist or not readable"
[ -d "$wantdir" ] && die "abort: $wantdir already exists"

# detect compression scheme
compression=`case $ext in
                  tar          ) echo "";;
                  tar.gz | tgz ) echo "z";;
                  tar.bz2      ) echo "j";;
                              *) false;;
             esac` || die "Unrecognized file format"

#
# Extract & move & cleanup
#
trap '[ -d "$tmpdir" ] && rm -rf "$tmpdir"' SIGINT
mkdir "$tmpdir" || die "Can't mkdir $tmpdir"
tar Cxf${compression} "$tmpdir" "$file" || { rm -rf "$tmpdir"; exit 1; }

[ "$(ls -1 $tmpdir)" == "$wantdir" ] && {
    # The archive unpacked the way we want
    mv "$tmpdir/$wantdir" . &&  rmdir "$tmpdir";
} || {
    # "Messy" unpack. Put it under the desired directory.
    echo "untar: creating $wantdir"
    mv "$tmpdir" "$wantdir";
}

