#! /usr/bin/env python

# Panflute
# Copyright (C) 2009 Paul Kuliniewicz <paul@kuliniewicz.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.

import panflute.applet.applet
import panflute.defs
import panflute.util

import dbus.mainloop.glib
import gnomeapplet
import logging
import os
import os.path
import sys


LOG_FORMAT = "%(levelname)s [%(name)s] %(message)s"


def applet_factory (applet, iid):
    """
    Fill in the content for a new applet.
    """

    logger = logging.getLogger ("panflute")
    logger.debug ("Initializing applet")
    panflute.applet.applet.Applet (applet)
    return True


def get_output_directory ():
    """
    Determine the place to save the applet's log files, creating it if it
    doesn't already exist.
    """

    data_home = os.getenv ("XDG_DATA_HOME", os.path.expanduser ("~/.local/share"))
    dirname = os.path.join (data_home, "panflute")

    try:
        os.makedirs (dirname, 0700)
    except OSError:
        # Directory already existing is not a failure
        pass

    return dirname


def setup_output ():
    """
    If invoked from the GNOME panel, limit logging and write output to files
    to facilitate debugging.  Otherwise, log everything and dump to the
    console.
    """

    for arg in sys.argv:
        if arg.startswith ("--oaf-activate-iid=") or arg.startswith ("--oaf-ior-fd="):
            dirname = get_output_directory ()
            mode = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
            perms = 0666

            outfile = os.open (os.path.join (dirname, "applet.stdout"), mode, perms)
            errfile = os.open (os.path.join (dirname, "applet.stderr"), mode, perms)
            logfile = file (os.path.join (dirname, "applet.log"), "w")

            os.dup2 (outfile, sys.stdout.fileno ())
            os.dup2 (errfile, sys.stderr.fileno ())
            logging.basicConfig (stream = logfile,
                                 level = logging.WARNING,
                                 format = LOG_FORMAT)

            os.close (outfile)
            os.close (errfile)

            return

    # No GNOME panel args found, so must have been run manually.

    logging.basicConfig (stream = sys.stderr,
                         level = logging.DEBUG,
                         format = LOG_FORMAT)


if __name__ == "__main__":
    setup_output ()
    logger = logging.getLogger ("panflute")

    panflute.util.init_i18n ()
    dbus.mainloop.glib.DBusGMainLoop (set_as_default = True)

    logger.debug ("Registering with Bonobo")
    gnomeapplet.bonobo_factory ("OAFIID:GNOME_Panflute_Applet_Factory",
                                gnomeapplet.Applet.__gtype__,
                                panflute.defs.PACKAGE,
                                panflute.defs.VERSION,
                                applet_factory)
