import re
import os
import argparse


regex = re.compile(r"""
   {\sNT_\("([^\)]+)"\)
   .+
   _\("([^)]+)"\)
   [,\s]+
   NT_\("([^)]+)"\)
""", re.X | re.M)


def parse_console_commands(source):
    with open(source, 'r') as f:
        text = f.read()
        match = regex.findall(text)

    __here__ = os.path.dirname(os.path.abspath(__file__))
    output = os.path.join(__here__, '..', 'lib', 'console_commands.py')

    with open(output, 'w') as f:
        f.write('# generated by almir/scripts/parse_console_commands.py\n')
        f.write('CONSOLE_COMMANDS = {\n')
        for name, desc, help_ in match:
            help_ = help_.replace('|', 'OR')
            f.write('    "%s": {"desc": "%s", "help": "%s"},\n' % (name, desc, help_))
        f.write('}')
        print 'written %s' % output


def main():
    parser = argparse.ArgumentParser(prog='parse_console_commands')
    parser.add_argument('bacula_source_directory')
    args = parser.parse_args()
    parse_console_commands(os.path.join(args.bacula_source_directory, 'bacula/src/dird/ua_cmds.c'))
