#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Turns an .ini file into a sequence of shell key=value definitions.
Each variable will be named [PREFIX__]SECTION__KEY unless --nosections is
passed in which case it will be named [PREFIX__]KEY.
"""
from __future__ import print_function

import sys, re
from optparse import OptionParser

try:
    import ConfigParser
except ImportError:
    import configparser as ConfigParser
try:
    from pipes import quote
except ImportError:
    from shlex import quote


def write(
    config, outfp=sys.stdout, prefix="", csh=False, fish=False, export=False, nosections=False
):
    for sec in config.sections():
        for opt, val in config.items(sec):
            opt = re.sub(r"^\W+", "", opt)
            opt = re.sub(r"\W+$", "", opt)
            if nosections:
                sec_opt = opt
            else:
                sec_opt = (sec + "__" if sec != "_" else "") + opt
            prefix_ = prefix + "__" if prefix else ""
            var = re.sub(r"\W+", "_", prefix_ + sec_opt)
            val = quote(val)
            if csh:
                if export:
                    line = "setenv {0} {1}".format(var, val)
                else:
                    line = "set {0}={1}".format(var, val)
            elif fish:
                if export:
                    line = "set -x {0} {1}".format(var, val)
                else:
                    line = "set {0} {1}".format(var, val)
            else:
                if export:
                    line = "export {0}={1}".format(var, val)
                else:
                    line = "{0}={1}".format(var, val)
            print(line, file=outfp)


def main():
    parser = OptionParser("%prog [options] [<FILE>]\n" + __doc__)
    parser.add_option(
        "-p",
        "--prefix",
        help="Prefix for all created variables (empty by default)",
        default="",
        metavar="PREFIX",
    )
    parser.add_option(
        "-o",
        "--output",
        help="Output file (stdout if omitted or '-'",
        default="-",
        metavar="FILE",
    )
    parser.add_option(
        "-x",
        "--export",
        help="Export variables into the environment",
        action="store_true",
    )
    parser.add_option(
        "-t", "--csh", "--tcsh", help="Generate csh/tcsh output", action="store_true"
    )
    parser.add_option(
        "-f", "--fish", help="Generate fish output", action="store_true"
    )
    parser.add_option(
        "-r", "--raw", help="Use raw parser (no interpolation)", action="store_true"
    )
    parser.add_option("-c", "--case", help="Case-sensitive keys", action="store_true")
    parser.add_option(
        "-n",
        "--nosections",
        help="Don't use sections; all sections will be combined and variables will be named [PREFIX__]KEY",
        action="store_true",
    )

    opts, args = parser.parse_args()

    if opts.raw:
        cp = ConfigParser.RawConfigParser()
    else:
        cp = ConfigParser.ConfigParser()

    if opts.case:
        cp.optionxform = str

    if args and args[0] not in ["-", ""]:
        cp.read(args[0])
    else:
        cp.readfp(sys.stdin)  # pylint: disable=deprecated-method

    if opts.output not in ["-", ""]:
        outfp = open(opts.output, "w")
    else:
        outfp = sys.stdout

    write(cp, outfp, opts.prefix, opts.csh, opts.fish, opts.export, opts.nosections)


if __name__ == "__main__":
    main()
