#! /usr/bin/env python

from main import client, HOME, USERHOME
from main.DisplayList import DisplayList

import sys
import os


_DISPLAYLIST = os.path.join(USERHOME, "displays")
_DSPLIST = DisplayList(_DISPLAYLIST)

def usage():

    print """
    Usage: gdesklets [option] <command> [arguments...]

    <command>: open <files>      (Opens the given display files)
               start             (Runs the gDesklets daemon)
               stop              (Stops the gDesklets daemon)
               list              (Lists open displays)
               restart           (Restarts the gDesklets daemon)
               profile <profile> (Switches to the given profile)
               profile           (Shows the current and the available profiles)
               shell             (Opens the graphical shell)
               slay              (Kills the daemon -- use in emergency)
               about             (Prints information about gDesklets)
               version           (Prints gDesklets version)
               help              (Displays this text)

    [option]: --translucent (Enables translucency on the freedesktop.org
                             XServer)
    """

daemon = None


def get_daemon():
    global daemon

    if (daemon):
        return daemon
    else:
        daemon = client.get_daemon()
        daemon.set_remove_command(os.path.abspath(sys.argv[0]) + " _remove")
        daemon.set_startup_command(os.path.abspath(sys.argv[0]) + " start")
        return daemon




def open_profile(profile):

    d = get_daemon()
    displays = _DSPLIST.get_displays(profile)
    for ident in displays:
        nil, path = _DSPLIST.lookup_display(ident)
        print "opening " + path
        d.open_display_with_id(path, ident)


def close_profile(profile):

    d = get_daemon()
    displays = _DSPLIST.get_displays(profile)
    for ident in displays:
        nil, path = _DSPLIST.lookup_display(ident)
        print "closing " + path
        d.close_display(ident)



if (len(sys.argv) <= 1):
    usage()
    sys.exit(1)

args = sys.argv[1:]
translucent = False
if ("--translucent" in args): args.remove("--translucent")

cmd = args[0]
files = args[1:]




if (cmd == "open"):
    d = get_daemon()
    for f in files:
        if (0 < f.find("://") < 8):
            path = f
        else:
            path = os.path.abspath(f)
        ident = d.open_display(path)
        profile = _DSPLIST.get_profile()
        _DSPLIST.add_display(profile, path, ident)
        _DSPLIST.commit()
        print "ID:", ident

elif (cmd == "start"):
    profile = _DSPLIST.get_profile()
    open_profile(profile)

elif (cmd == "stop"):
    d = get_daemon()
    print "Shutting down gdesklets-daemon..."
    d.shutdown()

elif (cmd == "shell"):
    cmd = "%s >/dev/null &" % (os.path.join(HOME, "gdesklets-shell"))
    os.system(cmd)
    
elif (cmd == "list"):
    current_profile = _DSPLIST.get_profile()
    display_list = _DSPLIST.get_displays(current_profile)
    for d in display_list:
        print _DSPLIST.lookup_display(d)[1]

elif (cmd == "restart"):
    print "Restarting gdesklets-daemon..."
    cmd = "%s stop && sleep 3 && %s start" % (sys.argv[0], sys.argv[0])
    os.system(cmd)

elif (cmd == "profile"):
    # get the current profile
    current_profile = _DSPLIST.get_profile()
    print "Current profile: %s" % (current_profile)

    if (files):
        new_profile = files[0]
        if (new_profile != current_profile):
            # close displays of the old profile
            close_profile(current_profile)
            # start displays of the new profile
            open_profile(new_profile)
        _DSPLIST.set_profile(new_profile)
        _DSPLIST.commit()
        print "New profile:     %s" % (new_profile)
    else:
        profiles_list = ", ".join(_DSPLIST.get_profiles())
        print "Available profiles: %s" % (profiles_list)

elif (cmd == "version"):
    d = get_daemon()
    name, version = d.version()
    print "This is %s, version %s." % (name, version)

elif (cmd == "about"):
    client.print_about()

elif (cmd == "help"):
    usage()

elif (cmd == "_remove"):
    ident = files[0]
    print "REMOVING", ident
    try:
        _DSPLIST.remove_display(ident)
        _DSPLIST.commit()
    except:
        print "Could not remove " + ident + "."

# emergency slaughtering
elif (cmd == "slay"):
    # FIXME: this only works with GNU ps; make it more portable
    os.system("kill -9 $(ps x -o '%p#%a' | tr -d ' ' | grep gdesklets-daemon "
              "| cut -f 1 -d#)")

else:
    print "Invalid command."
    usage()
