"""
Make a master image for an existing original
"""

import argparse
from functools import wraps
import logging
import os
from os.path import isfile, isdir, join, realpath, split, splitext
import re
import sys
import traceback
import uuid

DEFAULT_LOG_LEVEL = logging.ERROR
POSITIONAL_ARGUMENTS = [
    ['-l', '--loglevel', 'NOTSET',
        'desired logging level (' +
        'case-insensitive string: DEBUG, INFO, WARNING, or ERROR'],
    ['-v', '--verbose', False, 'verbose output (logging level == INFO)'],
    ['-w', '--veryverbose', False,
        'very verbose output (logging level == DEBUG)'],
    ['-m', '--hostname', 'images.isaw.nyu.edu', 'hostname for URL']
]


def main(args):
    """
    main function
    """
    # logger = logging.getLogger(sys._getframe().f_code.co_name)
    name = 'https://{}/{}'.format(args.hostname, args.name)
    guid = uuid.uuid5(uuid.NAMESPACE_URL, name)
    print(guid.urn)


if __name__ == "__main__":
    log_level = DEFAULT_LOG_LEVEL
    log_level_name = logging.getLevelName(log_level)
    logging.basicConfig(level=log_level, format='%(levelname)s: %(message)s')
    try:
        parser = argparse.ArgumentParser(
            description=__doc__,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        for p in POSITIONAL_ARGUMENTS:
            d = {
                'help': p[3]
            }
            if type(p[2]) == bool:
                if p[2] is False:
                    d['action'] = 'store_true'
                    d['default'] = False
                else:
                    d['action'] = 'store_false'
                    d['default'] = True
            else:
                d['default'] = p[2]
            parser.add_argument(
                p[0],
                p[1],
                **d)
        # example positional argument
        # parser.add_argument(
        #     'foo',
        #     metavar='N',
        #     type=str,
        #     nargs='1',
        #     help="foo is better than bar except when it isn't")
        parser.add_argument(
            'name',
            type=str,
            help='GUID5 name to use')
        args = parser.parse_args()
        if args.loglevel is not 'NOTSET':
            args_log_level = re.sub('\s+', '', args.loglevel.strip().upper())
            try:
                log_level = getattr(logging, args_log_level)
            except AttributeError:
                logging.error(
                    "command line option to set log_level failed "
                    "because '%s' is not a valid level name; using %s"
                    % (args_log_level, log_level_name))
        elif args.veryverbose:
            log_level = logging.INFO
        elif args.verbose:
            log_level = logging.WARNING
        log_level_name = logging.getLevelName(log_level)
        logging.basicConfig(level=log_level)
        if log_level != DEFAULT_LOG_LEVEL:
            logging.warning(
                "logging level changed to %s via command line option"
                % log_level_name)
        else:
            logging.info("using default logging level: %s" % log_level_name)
        logging.debug("command line: '%s'" % ' '.join(sys.argv))
        main(args)
        sys.exit(0)
    except KeyboardInterrupt as e:  # Ctrl-C
        raise e
    except SystemExit as e:  # sys.exit()
        raise e
    except Exception as e:
        print("ERROR, UNEXPECTED EXCEPTION")
        print(str(e))
        traceback.print_exc()
        os._exit(1)

@@ -67,50 +67,45 @@
 rse%0A
-from functools import wraps%0Aimport logging
+import logging%0Afrom lxml import etree
 %0Aimp
@@ -188,16 +188,44 @@
 port re%0A
+from slugify import slugify%0A
 import s
@@ -628,17 +628,17 @@
 %0A    %5B'-
-m
+n
 ', '--ho
@@ -696,122 +696,732 @@
 %0A%5D%0A%0A
-%0Adef main(args):%0A    %22%22%22%0A    main function%0A    %22%22%22%0A    # logger = logging.getLogger(sys._getframe().f_code.co_name
+RX_WHITESPACE = re.compile(r'%5Cs+')%0A%0A%0Adef get_text(tree, xpath):%0A    return ' '.join(%0A        etree.tostring(%0A            tree.xpath(xpath)%5B0%5D,%0A            method=%22text%22,%0A            encoding=%22unicode%22%0A        ).split())%0A%0A%0Adef main(args):%0A    %22%22%22%0A    main function%0A    %22%22%22%0A    # logger = logging.getLogger(sys._getframe().f_code.co_name)%0A    metapath = join(realpath(args.pkg_path), 'metadata.xml')%0A    meta = etree.parse(metapath)%0A    photographer = get_text(meta, %22//info%5B@type='isaw'%5D/photographer%22)%0A    title = get_text(meta, %22//info%5B@type='isaw'%5D/title%22)%0A    original = get_text(meta, %22//original-file-name%22)%0A    name = '/'.join((slugify(photographer), slugify(title), original))%0A    name = '-'.join(name.split()).lower(
 )%0A  
@@ -1467,21 +1467,16 @@
 stname, 
-args.
 name)%0A  
@@ -2680,20 +2680,24 @@
        '
-name
+pkg_path
 ',%0A     
@@ -2735,24 +2735,28 @@
 lp='
-GUID5 name to us
+path to image packag
 e')%0A

use metadata content to seed guid creation