#!/usr/bin/env python

# By Peter Bengtsson, June, 2005
# because he's too lazy to enter do
# $ tar -ztvf file
# $ # check that it gets extracted into one folder
# $ tar -zxvf file


__version__='1.0'

# TODO
# Support packaging as well as extracting

import sys, os, gzip, shutil, tarfile


def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        #print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)

if len(sys.argv[1:]) == 1 and \
     sys.argv[1].endswith('.tgz') or sys.argv[1].endswith('.tar.gz'):
    folder_names = []
    tfil = tarfile.open(sys.argv[1], 'r:gz')
    for name in tfil.getnames():
        if len(name.split(os.path.sep)) > 1:
            folder = name.split(os.path.sep)[0]
            if folder not in folder_names:
                folder_names.append(folder)
        
    if len(folder_names) == 1:
        # untar it
        for tarinfo in tfil:
            print tarinfo.name
            tfil.extract(tarinfo)
    else:
        print "Not tarred in one single folder. Create a new one?"
        folder = raw_input("Folder: ").strip()
        if folder:
            _mkdir(folder)
            for tarinfo in tfil:
                print os.path.join(folder, tarinfo.name)
                tfil.extract(tarinfo, folder)
        else:
            for tarinfo in tfil:
                print tarinfo.name
                tfil.extract(tarinfo)
        
        
