# w.c.s. - web application for online forms
# Copyright (C) 2005-2013  Entr'ouvert
#
# 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, see <http://www.gnu.org/licenses/>.

import os.path
import runpy
import warnings
import sys

from ..qommon.ctl import Command, make_option

class CmdRunScript(Command):
    '''Run a script within a given host publisher context'''

    name = 'runscript'

    def __init__(self):
        Command.__init__(self, [
                make_option('--vhost', metavar='VHOST', action='store',
                            dest='vhost'),
                ])

    def execute(self, base_options, sub_options, args):
        warnings.warn('Deprecated command, use management command', DeprecationWarning)
        from .. import publisher
        self.config.remove_option('main', 'error_log')
        publisher.WcsPublisher.configure(self.config)
        publisher = publisher.WcsPublisher.create_publisher(
                register_tld_names=False)
        publisher.app_dir = os.path.join(publisher.app_dir, sub_options.vhost)
        publisher.set_config()
        fullpath = os.path.dirname(os.path.abspath(args[0]))
        sys.path.insert(0, fullpath)
        module_name = os.path.splitext(os.path.basename(args[0]))[0]
        sys.argv = args
        runpy.run_module(module_name)

CmdRunScript.register()
