#!/usr/bin/env python
"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/qp/bin/qp $
$Id: qp 29086 2006-11-22 16:28:12Z 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.')

(options, args) = parser.parse_args()

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_interact:
    args.append(options.site_interact)
if options.quickrestart:
    args.append(options.quickrestart)

if args:
    for site_name in args :
        site = Site(site_name)
        try:
            site.get_configuration()
            sites.append(site)
        except ImportError, e:
            print "\nImport failed for site %s.\n" % site_name
else:
    # This imports all sites.
    sites = Site.get_sites().values()

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

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

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

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

if options.quickrestart:
    for site in sites:
        if site.get_name() == options.quickrestart:
            web_pid = site.is_web_running()
            if web_pid:
                kill(web_pid, SIGHUP)

if options.site_interact:
    for site in sites:
        if site.get_name() == options.site_interact:
            site.interaction()

if options.site_log:
    for site in sites:
        if site.get_name() == options.site_log:
            site.log_tail()

