#!/usr/bin/env python3

# Copyright (C) 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Xavi Garcia <xavi.garcia.mena@canonical.com>

import xml.etree.ElementTree as ET
import getopt, sys, os

def string_parameter(name, default_value, output):
    line = "    char const %s_DEFAULT[] = %s;" % (name.replace("-", "_").upper(), default_value)
    print(line, file=output)

def integer_parameter(name, default_value, output):
    line = "    int const %s_DEFAULT = %s;" % (name.replace("-", "_").upper(), default_value)
    print(line, file=output)

def bool_parameter(name, default_value, output):
    line = "    bool const %s_DEFAULT = %s;" % (name.replace("-", "_").upper(), default_value)
    print(line, file=output)

def process_default(name):
    print("WARNING: unsupported type found for parameter %s\n" % name)

options = {'i' : integer_parameter,
           's' : string_parameter,
           'b' : bool_parameter,
}

def usage():
    print("usage: parse-settings -i INPUT-SCHEMA-FILE -o OUTPUT-FILE")

def parse_args():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:o:h")
    except getopt.GetoptError as err:
        # print help information and exit:
        print(str(err)) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    input = None
    for o, a in opts:
        if o == "-h":
            usage()
            sys.exit()
        elif o == "-o":
            output = a
        elif o == "-i":
            input = a
        else:
            assert False, "unhandled option"

    if (input == None or output==None):
        usage()
        sys.exit()

    return (input, output)

def write_copyright(f):
    print("/*", file=f)
    print("* Copyright (C) 2015 Canonical Ltd.", file=f)
    print("*", file=f)
    print("* This program is free software: you can redistribute it and/or modify", file=f)
    print("* it under the terms of the GNU Lesser General Public License version 3 as", file=f)
    print("* published by the Free Software Foundation.", file=f)
    print("*", file=f)
    print("* This program is distributed in the hope that it will be useful,", file=f)
    print("* but WITHOUT ANY WARRANTY; without even the implied warranty of", file=f)
    print("* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the", file=f)
    print("* GNU Lesser General Public License for more details.", file=f)
    print("*", file=f)
    print("* You should have received a copy of the GNU Lesser General Public License", file=f)
    print("* along with this program.  If not, see <http://www.gnu.org/licenses/>.", file=f)
    print("*", file=f)
    print("* Authored by: This file is autogenerated by the parse-settings.py tool.", file=f)
    print("*/", file=f)

def write_header(f):
    write_copyright(f)
    print("#pragma once\n", file=f)
    print("namespace", file=f)
    print("{", file=f)

def write_footer(f):
    print("}", file=f)

def main():
    input, output = parse_args()

    if not os.path.exists(input):
        print("ERROR, input file %s does not exist\n" % input)
        usage()
        sys.exit()

    tree = ET.parse(input)
    root = tree.getroot()
    try:
        file_output = open(output, "w")
        write_header(file_output)
        for key in root.iter('key'):
            for default in key.iter('default'):
                try:
                    options[key.attrib.get('type')](key.attrib.get('name'), default.text, file_output)
                except KeyError:
                    process_default()
        write_footer(file_output)
    except IOError as e:
        print("I/O error({0}): {1}".format(e.errno, e.strerror))
    except:
        print("Unexpected error:", sys.exc_info()[0])
    finally:
        file_output.close()

if __name__ == '__main__':
    main()
