#!/usr/bin/python
# vim: encoding=utf-8
#expand *.in scripts for MSVC Builds
import os
import sys
import re
import string
import argparse

def get_version(srcroot):
    ver = {}
    RE_VERSION = re.compile(r'^m4_define\(\[(glib_\w+)\],\s*\[(\d+)\]\)')
    with open(os.path.join(srcroot, 'configure.ac'), 'r') as ac:
        for i in ac:
            mo = RE_VERSION.search(i)
            if mo:
                ver[mo.group(1).upper()] = int(mo.group(2))
    ver['GLIB_BINARY_AGE'] = 100 * ver['GLIB_MINOR_VERSION'] + ver['GLIB_MICRO_VERSION']
    ver['GLIB_VERSION'] = '%d.%d.%d' % (ver['GLIB_MAJOR_VERSION'],
                                        ver['GLIB_MINOR_VERSION'],
                                        ver['GLIB_MICRO_VERSION'])
    ver['LT_RELEASE'] = '%d.%d' % (ver['GLIB_MAJOR_VERSION'], ver['GLIB_MINOR_VERSION'])
    ver['LT_CURRENT'] = 100 * ver['GLIB_MINOR_VERSION'] + ver['GLIB_MICRO_VERSION'] - ver['GLIB_INTERFACE_AGE']
    ver['LT_REVISION'] = ver['GLIB_INTERFACE_AGE']
    ver['LT_AGE'] = ver['GLIB_BINARY_AGE'] - ver['GLIB_INTERFACE_AGE']
    ver['LT_CURRENT_MINUS_AGE'] = ver['LT_CURRENT'] - ver['LT_AGE']
    return ver

def process_in(src, dest, vars):
    RE_VARS = re.compile(r'@(\w+?)@')
    with open(src, 'r') as s:
        with open(dest, 'w') as d:
            for i in s:
                i = RE_VARS.sub(lambda x: str(vars[x.group(1)]), i)
                d.write(i)

def get_srcroot():
    if not os.path.isabs(__file__):
        path = os.path.abspath(__file__)
    else:
        path = __file__
    dirname = os.path.dirname(path)
    return os.path.abspath(os.path.join(dirname, '..', '..'))

def main(argv):
    prog_desc = 'Create Various autogenerated Win32-specific Source Files'
    parser = argparse.ArgumentParser(description=prog_desc)
    parser.add_argument('--glib-mkenums', dest='mkenums', action='store_const',
                        const=1,
                        help='Generate glib-mkenums')

    parser.add_argument('--perl', dest='perl', metavar='PATH',
                        default='C:\\Perl\\bin\\perl.exe',
                        action='store',
                        help='path to the perl interpretor (default: C:\\Perl\\bin\\perl.exe)')

    args = parser.parse_args()
    srcroot = get_srcroot()
    ver = get_version(srcroot)

    no_args = True

    if args.mkenums is not None:
        # Generate glib-mkenums script from glib-mkenums
        ver.update({'PERL_PATH': args.perl})

        target = os.path.join(srcroot, 'gobject', 'glib-mkenums')
        process_in(target + '.in',
                   target,
                   ver)
        no_args = False

    if no_args is True:
        raise SystemExit('Action argument required.  Please see %s --help for details.' % __file__)

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