#!/usr/bin/python
"""
dogtail-run-headless

This script runs a session within an X server, allowing dogtail scripts to be
run on systems with no graphic cards, among other things. Currently it can 
only start GNOME sessions.

Scripts are run in the current directory. After they are finished, dogtail can
optionally log out of the session, which will also termninate the X server.
"""

import optparse
from dogtail import sessions
import sys
import os.path


def findXServers(path = "/usr/bin"):
    l = [os.path.join(path, f) for f in os.listdir(path) if f[0] == 'X']
    s = set(os.path.realpath(p) for p in l)
    
    # VV hack for removing Xorg if /dev/fb0 is missing (on some ppc machines)
    if os.stat("/dev/fb0").st_gid == 0 and os.uname()[-1] == 'ppc64':
        s.discard('/usr/bin/X')
        s.discard('/usr/bin/Xorg') 
    
    return list(s)
def parse():
    yesno = ('y', 'n')
    sessions = ("GNOME",)
    usage = "usage: %prog: [options] {script [args]}"
    parser = optparse.OptionParser(usage=usage)

    parser.add_option("-s", "--session", type = "choice", 
            dest = "session", 
            choices = sessions, 
            help = "which session to use")
    parser.add_option("-x", "--x-server", type = "choice", 
            dest = "xserver", 
            choices = findXServers(), help = "which X server to use")
    parser.add_option("-l", "--logout", type = "choice", 
            dest = "logout", 
            choices = yesno,
            help = "attempt to log out of the session gracefully after" + 
                "script completion")
    parser.add_option("-t", "--terminate", type = "choice", 
            dest = "terminate",
            choices = yesno,
            help = "after script completion, and after any attempt to log" +
                "out, terminate the session")

    parser.set_defaults(session = sessions[0], logout = 'y', terminate = 'y')
    options, args = parser.parse_args()
    if not args:
        parser.print_usage()
        sys.exit(1)
    return options, args

def main():
    options, args = parse()
    if options.xserver:
        server = options.xserver
    else:
        print "Autodetection mode"
        servers = findXServers()
        server = servers[0]
        if '/usr/bin/Xorg' in servers: server = '/usr/bin/Xorg'
    if options.session == "GNOME":
        session = sessions.Session(sessionBinary = '/usr/bin/gnome-session', server=server, scriptCmdList = args)
    pid = session.start()
    scriptExitCode = session.script.exitCode
    if options.logout == 'y': session.attemptLogout()
    if options.terminate == 'y': session.stop()
    else: session.wait()
    sys.exit(scriptExitCode)

if __name__ == "__main__": main()
