#!/usr/bin/env python
import sys
import os
import sqlite3
import mpsconfig

def main(argv=None):
    options = mpsconfig.process_options(argv)
    
    dbfile = options.dbfile
    
    # Check if the dbfile exists
    if not os.path.isfile(dbfile):
        sys.stderr.write('Error: database "%s" does not exist\n' % dbfile)
        return 1

    if options.export_csv: mpsconfig.export_csv_files(dbfile, options.csv_path, options.verbose)
    if options.export_dump: mpsconfig.export_dump_file(dbfile, options.dump_path, options.verbose)

    if (options.export_sub or options.export_mapping or options.export_snl or options.export_edm or options.export_latex):
        # Connect to database
        connection = sqlite3.connect(dbfile)
        connection.row_factory = sqlite3.Row
        cursor = connection.cursor()
            
        if options.export_sub: mpsconfig.export_substitution_file(cursor, options.substitutions_path, options.verbose)
        if options.export_mapping: mpsconfig.export_mapping_file(cursor, options.mapping_path, options.verbose)
        if options.export_snl: mpsconfig.export_snl_program(cursor, options.snl_path, options.verbose)
        if options.export_edm: mpsconfig.export_edm_files(cursor, options.edm_path, options.verbose)
        if options.export_latex: mpsconfig.export_latex_file(cursor, options.latex_path, options.latex_rev, options.embed_latex, options.verbose)
    
        connection.close()
    
    return 0


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



