#!/usr/bin/env python
#  -*- mode: python; -*-
#============================================================================
# Copyright (C) 2004 Tom Wilkie <tw275@cl.cam.ac.uk>
# Copyright (C) 2004 Mike Wray  <mike.wray@hp.com>
#============================================================================

"""SV web interface Lives in /usr/sbin.
   Provides pretty HTML management interface.

   Run:

   sv start

   The daemon is stopped with:

   sv stop
   
   The daemon will be accessible from http://localhost:8080/
"""
import os
import sys
import re

# add fallback path for non-native python path installs if needed
sys.path.append('/usr/lib/python')
from xen.xend.server.params import XEND_PID_FILE

class CheckError(ValueError):
    pass

def hline():
    print >>sys.stderr, "*" * 70

def msg(message):
    print >>sys.stderr, "*" * 3, message

def check_logging():
    """Check python logging is installed and raise an error if not.
    Logging is standard from Python 2.3 on.
    """
    try:
        import logging
    except ImportError:
        hline()
        msg("Python logging is not installed.")
        msg("Use 'make install-logging' at the xen root to install.")
        msg("")
        msg("Alternatively download and install from")
        msg("http://www.red-dove.com/python_logging.html")
        hline()
        raise CheckError("logging is not installed")

def check_twisted_version():
    """Check twisted is installed with a supported version and print a warning if not.
    Raises an error if twisted is not installed.
    """
    # Supported twisted release and major version.
    RELEASE = 1
    MAJOR   = 3
    try:
        from twisted.copyright import version
    except ImportError:
        hline()
        msg("The Twisted framework is not installed.")
        msg("Use 'make install-twisted' at the xen root to install.")
        msg("")
        msg("Alternatively download and install version %d.%d or higher" % (RELEASE, MAJOR))
        msg("from http://www.twistedmatrix.com/products")
        hline()
        raise CheckError("twisted is not installed")
        
    
    (release, major, minor) = version.split('.')
    release = int(release)
    major = int(major)
    if release > RELEASE: return
    if release == RELEASE and major >= MAJOR: return
    hline()
    msg("Warning: Twisted version not supported: %s" % version)
    msg("Use Twisted version %d.%d.0 or higher" % (RELEASE, MAJOR))
    hline()
    
def check_xend():
    """Check xend is running
    """
    
    if not os.path.isfile(XEND_PID_FILE) or not os.path.getsize(XEND_PID_FILE):
    	hline()
        msg( "Warning: Xend has not been detected as running." )
        msg( "Please start it immediately with: xend start " )
        hline()
        return 0
        
    # Read the pid of the previous invocation and search active process list.
    pid = open(XEND_PID_FILE, 'r').read()
    lines = os.popen('ps ' + pid + ' 2>/dev/null').readlines()
    for line in lines:
        if re.search('^ *' + pid + '.+xend', line):
            return 1

    hline()
    msg( "Warning: Xend has not been detected as running." )
    msg( "Please start it immediately with: xend start " )
    hline() 
    return 0
    
def main():
    try:
        check_logging()
        check_twisted_version()
        check_xend()
    except CheckError:
        sys.exit(1)
    
    from xen.sv import Daemon

    daemon = Daemon.instance()
    
    if not sys.argv[1:]:
        print 'usage: %s {start|stop|restart}' % sys.argv[0]
    elif os.fork():
        pid, status = os.wait()
        return status >> 8
    elif sys.argv[1] == 'start':
        return daemon.start()
    elif sys.argv[1] == 'stop':
        return daemon.stop()
    elif sys.argv[1] == 'restart':
        return daemon.stop() or daemon.start()
    else:
        print 'not an option:', sys.argv[1]
    return 1

if __name__ == '__main__':
    sys.exit(main())
