#!/bin/python
# -*- Mode: python; indent-tabs-mode: nil -*-

# Copyright (c) 2014 Shaun McCance <shaunm@gnome.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import argparse
import os
import sys

import mallard.ducktype

if __name__ == '__main__':
    argparser = argparse.ArgumentParser()
    argparser.add_argument('-o', '--output', nargs='?',
                           help='specify the output file or directory')
    argparser.add_argument('files', nargs='+',
                           help='list of input duck files')
    args = argparser.parse_args()
    if args.output is not None:
        if len(args.files) > 1 and not os.path.isdir(args.output):
            sys.stderr.write('Output must be a directory for multiple files\n')
            sys.exit(1)
    for file in args.files:
        try:
            parser = mallard.ducktype.DuckParser()
            parser.parse_file(file)
            parser.finish()
        except mallard.ducktype.SyntaxError as e:
            sys.stderr.write(e.fullmessage + '\n')
        basename = os.path.basename(file)
        if basename.endswith('.duck'):
            basename = basename[:-5]
        if args.output is None:
            outfile = os.path.join(os.path.dirname(file), basename + '.page')
        elif os.path.isdir(args.output):
            # FIXME: try to recreate directory structure?
            outfile = os.path.join(args.output, basename + '.page')
        else:
            outfile = args.output
        parser.document.write_xml(outfile)
