#!/usr/bin/env python
import re
import sys


def read_conf_into_dict(file_path):
    settings = {}
    with open(file_path) as fh:
        for line in fh:
            if re.match(r'\s*(?:#|$)', line):
                continue
            key, value = map(str.strip, line.split('=', 1))
            settings[key] = value
    return settings


def get_script_contents(config, interpreter):
    contents = '#!/bin/bash\n'
    build_sys = config['build-sys']

    if build_sys == 'none':
        contents += '# empty'

    elif build_sys == 'python-distutils':
        contents += interpreter + ' '
        build_file = config.get('build-file', '')
        if build_file:
            build_opt = config.get('build-opt', '')
            contents += (build_file + ' ' + build_opt).rstrip()
        else:
            contents += 'setup.py build'

    elif build_sys == 'other':
        build_cmd = config.get('build-cmd', '')
        contents += build_cmd

    contents += '\n'

    return contents


def array_get(array, idx, default):
    try:
        return array[idx]
    except IndexError:
        return default


def main(argv):
    package_conf = array_get(argv, 1, 'package.conf')
    interpreter = array_get(argv, 2, 'python')
    output = array_get(argv, 3, '')

    config = read_conf_into_dict(package_conf)
    contents = get_script_contents(config, interpreter)
    if output and output != '-':
        with open(output, 'w') as output_fh:
            output_fh.write(contents)
    else:
        sys.stdout.write(contents)

    return 0


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

