#!/usr/bin/env python
"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/qp/bin/qp $
$Id: qp 29041 2006-11-08 14:49:50Z dbinger $
"""
import os
if 'QP' not in os.environ:
    os.environ['QP'] = '1'
assert os.environ['QP'] == '1'

from qp.lib.site import Site
from qp.lib.util import import_object
import sys
from os import kill
from signal import SIGHUP
from optparse import OptionParser
import qp.sites

parser = OptionParser()
parser.set_usage("qp [options] [start|stop|restart] [site]*")
parser.set_description('''\
Control the servers for the sites in your qp installation.
No options is the same as "--status".
"stop" is the same as "--stop".
"start" is the same as "--start".
"restart" is the same as "--stop --start".

If "--stop" and "--start" are both present and the durus server
is already running, only the web server is restarted.

The script searches for sites in the qp.sites package, which
in turn searches through the following list, by default.
    ''' + "\n    ".join(path for path in qp.sites.sites_path) + "\n")

def format_description(self, *args):
    return self.parser.get_description()
parser.format_description = format_description

parser.add_option(
    '-u', '--start', dest='start', default=False, action='store_true',
    help="Start the durus and web servers.")
parser.add_option(
    '-d', '--stop', dest='stop', default=False, action='store_true',
    help="Stop the durus and web servers.")
parser.add_option(
    '-q', '--quickrestart', dest='quickrestart', action='store',
    help='Quick restart of the web server(s) of the named site.')
parser.add_option(
    '-v', '--status', dest='status', default=False, action='store_true',
    help='Show the current status of the durus and web servers.')
parser.add_option(
    '-c', '--configuration', dest='show', default=False, action='store_true',
    help='Show the site configuration.')
parser.add_option(
    '-l', '--log', dest='site_log', action='store',
    help='tail -f the log for the named site.')
parser.add_option(
    '-i', '--interact', dest='site_interact', action='store',
    help='Open an interactive session with the named site.')
parser.add_option(
    '-s', '--site', dest='site', default=[], action='append',
    help=("Start and/or stop only the named site.  "
          "Default is all sites in sites package."))
parser.add_option(
    '-b', '--base', dest='base',
    default=None, action='store',
    help=(
    "A package with sites.  The QP_SITES environment variable will be\n"
    "set to be the directory where this package is found."))
parser.add_option(
    '--build', dest='build', default=False, action='store_true',
    help=('Compile cgi2scgi executable(s).  '
          'You can use these with any cgi-supporting web server. '
          'This prints config lines for Apache.'))

(options, args) = parser.parse_args()

def no_sites():
    print "Could not find sites in any of these places:"
    for path in qp.sites.__path__:
        print "   ", path
    raise SystemExit

if options.base is not None:
    try:
        os.environ['QP_SITES'] = import_object(options.base + '.__path__')[0]
    except ImportError:
        print "Could not import package %r" % options.base
        raise SystemExit

try:
    all_sites = Site.get_sites()
except ImportError:
    no_sites()

if 'start' in args:
    options.start = True
    args.remove('start')
if 'stop' in args:
    options.stop = True
    args.remove('stop')
if 'restart' in args:
    options.start = True
    options.stop = True
    args.remove('restart')

sites = []
if options.site:
    sites = [v for k, v in all_sites.items() if k in options.site]
    if not sites:
        print "Site not found: %r" % options.site
        raise SystemExit
if args:
    for arg in args:
        if arg in all_sites and arg not in sites:
            sites.append(all_sites[arg])
        else:
            print "Site not found: %r" % arg
            raise SystemExit
if not sites:
    sites = all_sites.values()
if not sites:
    no_sites()


for site in sites:
    if options.stop:
        site.stop_web()
        site.stop_durus()
    if options.start:
        site.start_durus()
        site.start_web()

if options.build:
    for site in sites:
        site.build()

if options.show:
    for site in sites:
        site.show()

if (options.status or not (options.stop or
                           options.start or
                           options.build or
                           options.site_log or
                           options.site_interact or
                           options.quickrestart or
                           options.show)):
    for site in sites:
        site.status()

if options.quickrestart:
    web_pid = all_sites[options.quickrestart].is_web_running()
    if web_pid:
        kill(web_pid, SIGHUP)

if options.site_interact:
    all_sites[options.site_interact].interaction()

if options.site_log:
    all_sites[options.site_log].log_tail()

