#-------------------------------------------------------------------------------------------------
# Copyright (c) International Business Machines Corp., 2014
#
# IBM XIV Storage System Software
#
# Licensed materials provided under the terms of the IBM International Program
# License Agreement. See the Software
# licensing materials that came with the IBM XIV Storage System for terms and
# conditions.
#
#-------------------------------------------------------------------------------------------------
import sys, zipfile, os, traceback
from os.path import isdir, join, normpath, split

# Function to unzipping the contents of the zip file
def unzip(path, zip):
    if not isdir(path):
        os.makedirs(path)    
    for each in zip.namelist():
        print "Extracting " + os.path.basename(each) + " ..."

        if not each.endswith('/'): 
            root, name = split(each)
            directory = normpath(join(path, root))
            if not isdir(directory):
                os.makedirs(directory)
            file(join(directory, name), 'wb').write(zip.read(each))

if __name__ == '__main__':
    if (3 != len(sys.argv)):
        print "Usage: xpyv unzip.py <zip_file> <output_folder>"
        sys.exit(0)
    try:
        infile = sys.argv[1]
        outfol = sys.argv[2]
        zip = zipfile.ZipFile(infile, 'r')
        unzip(outfol, zip)
        zip.close()
    except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n    " + \
            str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"
        print pymsg

