#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Open a Zine Shell
    ~~~~~~~~~~~~~~~~~

    This script opens a shell for Zine.

    :copyright: (c) 2009 by the Zine Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
import sys
from os.path import abspath, join, pardir, isfile, dirname
from optparse import OptionParser
from werkzeug.script import make_shell


sys.path.append(dirname(__file__))
from _init_zine import find_instance


def init_func(instance):
    from zine import setup
    app = setup(instance)
    del setup
    from zine import models
    from zine.database import db
    return locals()


def main():
    parser = OptionParser(usage='%prog [options]')
    parser.add_option('--no-ipython', dest='no_ipython', action='store_true',
                      help='Do not launch ipython, even if present.')
    parser.add_option('--instance', '-I', dest='instance',
                      help='Use the path provided as Zine instance.')
    options, args = parser.parse_args()
    if args:
        parser.error('incorrect number of arguments')
    instance = options.instance or find_instance()
    if instance is None:
        parser.error('instance not found.  Specify path to instance')

    make_shell(lambda: init_func(instance), banner='Zine Shell [%s]' %
               abspath(instance))(ipython=not options.no_ipython)


if __name__ == '__main__':
    main()
