#!/usr/bin/env python
"""
$URL: svn+ssh://sting.mems-exchange.org/repos/trunk/DurusWorks/qp/__main__.py $
$Id: __main__.py 30561 2008-03-10 22:20:04Z dbinger $
"""
from qp.lib.site import Site
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_true',
    help='Quick restart of the web server(s) of the named sites.')
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_true',
    help='tail -f the log for the last named site.')
parser.add_option(
    '-i', '--interact', dest='site_interact', action='store_true',
    help='Open an interactive session with the last named site.')

(options, args) = parser.parse_args()

if 'start' in args:
    options.stop = True
    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 args:
    for site_name in args :
        site = Site(site_name)
        try:
            site.get_configuration()
            sites.append(site)
        except ImportError:
            e = sys.exc_info()[1]
            print("\nImport failed for site %s (%s).\n" % (site_name, e))
else:
    # This imports all sites.
    sites = list(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.quickrestart:
        web_pid = site.is_web_running()
        if web_pid:
            kill(web_pid, SIGHUP)
    if options.show:
        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)):
        site.status()

if options.site_interact:
    sites[-1].interaction()

if options.site_log:
    sites[-1].log_tail()
