#! /usr/bin/python

# Copyright (C) 2010 Tresys Technology, LLC
#
#  Author(s): Karl MacMillan <kmacmillan@tresys.com>
#             Jason Dana <jdana@tresys.com>
#             Francisco Slavin <fslavin@tresys.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  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, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA



from scc import parser, output, normalize, transform, config

from optparse import OptionParser

import sys

def parse_options():
    usage = "usage: %prog [options] input_file [input_file . . .]"
    parser = OptionParser(usage=usage, version="%prog " + config.VERSION)
    parser.add_option("-o", dest="out_fname", default="out.xml",
                      help="name of output file. Default is out.xml. Use '-' for stdout")
    parser.add_option("-i", dest="id_fname", default="id.ini",
                      help="name of id database - default is id.ini")
    parser.add_option("-d", dest="debug", action="store_true",
                      default=False, help="produce parsing debugging information")
    parser.add_option("-s", dest="diff_files", action="store_true",
                      default=False, help="output a separate OVAL file for each input file using the input file's name")
    parser.add_option("-p", dest="id_prefix", default="oval:scc.generated.id",
                      help="OVAL ID prefix.  Default is oval:scc.generated.id")

    (options, args) = parser.parse_args()

    if len(args) < 1:
        sys.stderr.write("At least one input is required!\n\n")
        parser.print_help()
        sys.exit(1)

    return (options, args)
        
def output_oval(out_fname, oval):
    if out_fname == "-":
        print output.pretty_print(oval)
    else:
        try:
            f = open(out_fname, "wb")
            f.write(output.pretty_print(oval) + "\n")
        except IOError, e:
            sys.stderr.write("Could not write output: %s!" % str(e))
            sys.exit(1)

def main():
    (options, args) = parse_options()
    
    oval = None
    for fname in args:
        try:
            f = open(fname)
        except IOError, e:
            sys.stderr.write("Could not open input file: %s \n %s\n" % (fname, str(e)))
            sys.exit(1)
        tree = parser.parse(f, options.debug)
        try:
            normalize.normalize_tree(tree, options.id_fname, options.id_prefix, options.debug)
            oval = transform.transform(tree, oval)
        except parser.ParseException, e:
            sys.stderr.write("Compilation error:\n")
            sys.stderr.write("\t" + str(e) + "\n")
            sys.exit(1)
        except Exception, e:
            sys.stderr.write("Error: %s\n" % str(e))
            sys.exit(1)
        
        if options.diff_files:
            transform.clear_empty(oval)
            out_file = fname.split('.sc')[0] + '.xml'
            output_oval(out_file, oval)
            oval = None
        
    if not options.diff_files:
        transform.clear_empty(oval)
        output_oval(options.out_fname, oval)

    

if __name__ == "__main__":
    main()
