#! /usr/bin/env python

from main import client, HOME, USERHOME, LOGFILE, PID_PATH
from main.DisplayList import DisplayList
from utils import i18n

import sys
import os
import __builtin__
__builtin__._ = i18n.Translator("gdesklets")


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


def usage_and_exit():

    """ prints how to use gdesklets"""

    print _(
        "Usage: gdesklets [option] <command> [arguments...]\n"
        "\n"
        "\t<command>\n"
        "\t\topen    <files>   (Opens the given display files)\n"
        "\t\tstart             (Runs the gDesklets daemon, this is default)\n"
        "\t\tstop              (Stops the gDesklets daemon)\n"
        "\t\tlist              (Lists open displays)\n"
        "\t\trestart           (Restarts the gDesklets daemon)\n"
        "\t\tprofile <profile> (Switches to the given profile)\n"
        "\t\tprofile           (Shows the current and the available profiles)\n"
        "\t\tshell             (Opens the graphical shell)\n"
        "\t\tslay              (Kills the daemon -- use in emergency)\n"
        "\t\tstatus            (Checks daemon status)\n"
        "\t\tabout             (Prints information about gDesklets)\n"
        "\t\tversion           (Prints gDesklets version)\n"
        "\t\thelp              (Displays this text)\n"
        "\n"
        "\t[option]\n"
        "\t\t--translucent (enables translucency on the xorg servers)\n"
        )
    sys.exit(1)


def get_daemon():

    """ Returns the daemon if available, otherwise informs the user that
        something went wrong """

    try:
        ndaemon = client.get_daemon()
        ndaemon.set_remove_command(os.path.abspath(sys.argv[0]) + " _remove")
        ndaemon.set_startup_command(os.path.abspath(sys.argv[0]) + " start")

        return ndaemon

    except StandardError:
        print >> sys.stderr, ("Error while starting gdesklets-daemon\n"
                              "More information about this crash is available"
                              "in \"%s\"." % (LOGFILE,))

def open_profile(profile):

    """ Opens passed profile """

    mydaemon = get_daemon()
    displays = _DSPLIST.get_displays(profile)
    for myident in displays:
        mypath = _DSPLIST.lookup_display(myident)[-1]
        mydaemon.open_display_with_id(mypath, myident)


def close_profile(profile):

    """ Closes passed profile """

    mydaemon = get_daemon()
    displays = _DSPLIST.get_displays(profile)
    for myident in displays:
        mydaemon.close_display(myident)


try:
    args = sys.argv[1:]

    try:
        args.remove("--translucent")
    except StandardError:
        pass

    # remove gnome-session crap
    # "usage:  %s [--sm-config-prefix prefix] [--sm-client-id id] [--debug]\n"
    try:
        args.remove('--debug')
    except StandardError:
        pass

    try:
        i = args.index('--sm-config-prefix')
        del args[i:i+2]
    except StandardError:
        pass

    try:
        i = args.index('--sm-client-id')
        del args[i:i+2]
    except StandardError:
        pass
    # done removing gnome-session crap

    if not args:
        args = ['start']

    cmd = args.pop(0)
    files = args

except StandardError:
    usage_and_exit()


if (cmd == "open"):

    if (len(files) == 0):
        usage_and_exit()

    daemon = get_daemon()
    for item in files:
        if (0 < item.find("://") < 8):
            path = item
        else:
            path = os.path.abspath(item)
        ident = daemon.open_display(path)
        prof = _DSPLIST.get_profile()
        _DSPLIST.add_display(prof, path, ident)
        _DSPLIST.commit()

elif (cmd == "start"):
    print _("Starting gdesklets-daemon...")
    myprofile = _DSPLIST.get_profile()
    open_profile(myprofile)

elif (cmd == "stop"):
    if client.daemon_is_running():
        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"):
    myprofile = _DSPLIST.get_profile()
    display_list = _DSPLIST.get_displays(myprofile)

    if (display_list):
        print _("Currently open displays in profile '%s':" % myprofile)
        for d in display_list:
            print _DSPLIST.lookup_display(d)[1]
    else:
        print _("Currently there aren't any displays in profile '%s'" \
                % myprofile)

elif (cmd == "restart"):
    print _("Restarting gdesklets-daemon...")

    if client.daemon_is_running():
        cmd = "%s stop && sleep 3 && %s start" % (sys.argv[0], sys.argv[0])
    else:
        cmd = "%s start" % (sys.argv[0],)

    os.system(cmd)

elif (cmd == "status"):

    if client.daemon_is_running():
        print _("gdesklets-daemon is running")
    else:
        print _("gdesklets-daemon is not running")

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"):
    d = get_daemon()
    name, copy_right, gnu = d.about()
    print "%s\n%s\n\n%s" % (name, copy_right, gnu)

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

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

elif (cmd == "slay"):

    import os
    import time
    import signal

    try:
        pid = int(open(PID_PATH).read())
    except:
        sys.exit("Nothing to slay")

    for sig in signal.SIGINT, signal.SIGTERM, signal.SIGKILL:
        
        try:
            os.kill(pid, sig)
        except OSError:
            break
        
        time.sleep(1)

    try:
        os.remove(PID_PATH)
    except OSError:
        pass

else:
    print _("Invalid command. Please try one of the following commands!")
    usage_and_exit()

