#!/usr/bin/python -tt
# Schedwi
# Copyright (C) 2011-2013 Herve Quatremain
#
# This file is part of Schedwi.
#
# Schedwi 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 3 of the License, or
# (at your option) any later version.
#
# Schedwi 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/>.


"""Main"""

from optparse import OptionParser
import os.path
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import locale
import gettext
sys.path.insert(0, '/usr/lib/python2.7/dist-packages/schedwisrv')

import parse_config
import config
import cmd_loop
import sql_session

locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(config.PACKAGE, config.LOCALEDIR)
gettext.textdomain(config.PACKAGE)
gettext.install(config.PACKAGE, config.LOCALEDIR, True)

parser = OptionParser(version="%prog " + config.PACKAGE_VERSION)
parser.add_option(
    "-c", "--config", dest="conf_file", metavar="FILE",
    help=_("use the configuration file FILE rather than the default one"))
(options, args) = parser.parse_args()

if options.conf_file is not None and not os.path.isfile(options.conf_file):
    sys.stderr.write(_("%(file)s is not a file\n") %
                     {"file": options.conf_file})
    sys.exit(1)

parse_config.parse(options.conf_file)
sql = sql_session.SqlSession(drivername=parse_config.DBI_DRIVERNAME,
                             user=parse_config.DBI_USER,
                             password=parse_config.DBI_PASSWORD,
                             hostname=parse_config.DBI_DBHOSTNAME,
                             dbname=parse_config.DBI_DBNAME,
                             dbdir=parse_config.DBI_DBDIR)
if args:
    loop = cmd_loop.Loop(sql, interactive=False)
    config.ISATTY_STDOUT = False
    config.ISATTY_STDIN = False
    cmd = list()
    cmd.append(args.pop(0))
    for arg in args:
        cmd.append('"' + arg + '"')
    sys.exit(loop.onecmd(' '.join(cmd)))
else:
    loop = cmd_loop.Loop(sql, interactive=True)
    title = config.ISATTY_STDIN
    while 1:
        try:
            if title:
                title = False
                msg = (_("Schedwi version %(vers)s") %
                       {"vers": config.PACKAGE_VERSION} +
                       "\n" + _("Enter `help' for instructions"))
                loop.cmdloop(msg.encode('utf-8'))
            else:
                loop.cmdloop('')
        except KeyboardInterrupt:
            print ''
            pass
