import collections
import logging
import os
import re
import sys

import netaddr

from hades.common.cli import ArgumentParser, parser as parent_parser
from hades.config.loader import load_config

logger = logging.getLogger('hades.config.export')
shell_types = (int, str, bool, netaddr.IPAddress, netaddr.IPNetwork)
pattern = re.compile(r'([^a-zA-Z0-9_])')
replacement = r'\\\1'


def escape(value):
    """
    Escape a string for shell argument use.
    shlex.quote breaks unfortunately on certain strings
    """
    return pattern.sub(replacement, str(value))


def main():
    parser = ArgumentParser(description='Export options as shell '
                                                 'variables',
                            parents=[parent_parser])
    args = parser.parse_args()
    config = load_config(args.config)
    for name, value in config.items():
        escaped_name = escape(str(name))
        if isinstance(value, shell_types):
            print("export {}={}".format(escaped_name, escape(value)))
        elif isinstance(value, collections.Mapping):
            print("declare -A {}".format(name))
            for k, v in value.items():
                if isinstance(v, shell_types):
                    print("{}[{}]={}".format(escaped_name, escape(str(k)),
                                             escape(str(v))))
            print("export {}".format(escaped_name))
        elif isinstance(value, collections.Sequence):
            print("declare -a {}".format(name))
            for index, v in enumerate(value):
                if isinstance(v, shell_types):
                    print("{}[{}]={}".format(escaped_name, index,
                                             escape(str(v))))
            print("export {}".format(escaped_name))


if __name__ == '__main__':
    sys.exit(main())

@@ -963,23 +963,16 @@
  print(%22
-export 
 %7B%7D=%7B%7D%22.f
@@ -1003,24 +1003,24 @@
 pe(value)))%0A
+
         elif
@@ -1335,60 +1335,8 @@
 )))%0A
-            print(%22export %7B%7D%22.format(escaped_name))%0A
     
@@ -1592,16 +1592,16 @@
  index,%0A
+
         
@@ -1658,60 +1658,8 @@
 )))%0A
-            print(%22export %7B%7D%22.format(escaped_name))%0A
 %0A%0Aif

Remove export declarations in shell export