#-------------------------------------------------------------------------------------------------
# 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

def _zip(path, zip, keep):
    path = os.path.normpath(path)

    for (dirpath, dirnames, filenames) in os.walk(path):
        for file in filenames:
            # Ignore .lock files
            if not file.endswith('.lock'):
                print "Adding %s..." % os.path.join(path, dirpath, file)
                try:
                    if keep:
                        zip.write(os.path.join(dirpath, file),
                                  os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):]))
                    else:
                        zip.write(os.path.join(dirpath, file),            
                                  os.path.join(dirpath[len(path):], file)) 

                except Exception, e:
                    print "    Error adding %s: %s" % (file, e)
    return None

if __name__ == '__main__':
    if (3 != len(sys.argv)):
        print "Usage: xpyv zip.py <input_folder> <output_zip_file>"
        sys.exit(0)
    try:
        infolder = sys.argv[1]
        outfile = sys.argv[2]
        try:
            zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
            _zip(infolder, zip, True)
            zip.close()
        except RuntimeError:
            if os.path.exists(outfile):
                os.unlink(outfile)
                zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
                _zip(infolder, zip, True)
                zip.close()
                print "    Unable to compress zip file contents."

        print "Zip file created successfully"
    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
