#!/usr/bin/python
import sys, os
import argparse
from subprocess import call

version = '1.0'

def unzip(f):
    print 'start unzip: ' + f

    f_name, f_ex = os.path.splitext(f)
    f_path, f_ab_name = os.path.split(f_name)

    """
    print 'f_path: ' + f_path
    print 'f_ab_name: ' + f_ab_name
    print 'f_ex: ' + f_ex
    """

    if f_ex == '.zip':
        print 'filetype: .zip'
        call(['mkdir', f_ab_name])
        call(['unzip', f, '-d', f_ab_name])
    elif f_ex == '.tar':
        print 'filetype: .tar'
        call(['mkdir', f_ab_name])
        call(['tar', '-xvf', f, '-C', f_ab_name])
    elif f_ex == '.gz':
        f_ab_name2 ,f_ex2 = os.path.splitext(f_ab_name)
        print 'f_ab_name2: ' + f_ab_name2
        print 'f_ex2: ' + f_ex2
        if f_ex2 == '.tar':
            print 'filetype: .tar.gz'
            call(['mkdir', f_ab_name2])
            call(['tar', '-zxvf', f, '-C', f_ab_name2])
        else:   # just .gz
            print 'filetype: .gz'
            call(['mkdir', f_ab_name])
            call(['gzip', '-d', f])
    else:
        raise NameError


def main(argv):
    parser = argparse.ArgumentParser(description='\'uz\' is a tool that unzip mutli-type zip files with auto format detection.')
    parser.add_argument('input_file', action='store') 
    parser.add_argument('--version', action='version', version='%(prog)s '+version)
    args = parser.parse_args()
    try:
        unzip(args.input_file)
    except NameError:
        print "sorry, this is an un-supported file type"

if __name__ == "__main__":
   main(sys.argv[1:])
