#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4

##
## Copyright (C) 2009 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## 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 Lesser 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., or visit: http://www.gnu.org/.
##
##
## Author(s):   George Y. Kussumoto     <george@async.com.br>
##
##

import os.path
import sys

from stoqlib.database.tables import get_table_types
from stoqlib.database.runtime import new_transaction, get_connection
from stoqlib.lib.parameters import sysparam

from stoq.lib.options import get_option_parser
from stoq.lib.startup import setup


def main(args):
    parser = get_option_parser()
    options, args = parser.parse_args(args)

    if len(args) != 2:
        parser.print_help()

    script = args[-1]
    if not os.path.isfile(script):
        print 'File not found: %s' % script
        return 1

    setup(options=options, register_station=False, check_schema=False)
    ns = locals().copy()
    for table in get_table_types():
        ns[table.__name__] = table

    ns['conn'] = conn = get_connection()
    if options.sqldebug:
        conn.debug = True
    ns['trans'] = new_transaction()
    ns['sysparam'] = sysparam

    for name in ('sqlobject', 'sqlobject.sqlbuilder',
                 'stoqlib.database.runtime', 'stoqlib.lib.interfaces',
                 'stoqlib.domain.interfaces'):
        mod = __import__(name, {}, {}, ' ')
        ns.update(mod.__dict__)

    execfile(script, ns)
    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv))
