#!/usr/bin/python2
# -*- coding: UTF-8 -*-

import __builtin__
from utils import i18n
__builtin__._ = i18n.Translator("gdesklets")

from config import settings
from utils.logger import SyncWriter
from utils.UpdateChecker import UpdateChecker
from main import transition, LOGFILE
from main.Starter import Starter

import atexit
import main
import gobject
import gtk
import os
import pygtk
import sys
import utils
# No big deal if this fails
try:
    from dbus.mainloop.glib import DBusGMainLoop
except:
    def DBusGMainLoop(set_as_default = True):
        pass



# setup GTK
try:
    pygtk.require("2.0")
except StandardError:
    print _("You need a recent version of PyGTK to run this program.\n")
    sys.exit(1983)


def _detach_as_daemon():

    """
    Performs the UNIX double fork to detach as a daemon process as described at
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 and
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
    """

    try:
        pid = os.fork()
        if (pid > 0):
            os._exit(0)

        os.chdir("/")
        os.setsid()

        pid = os.fork()
        if (pid > 0):
            os._exit(0)

    except StandardError:
        print _("Could not fork daemon.\n")
        sys.exit(1)


def _write_pid():

    try:
        utils.makedirs(main.USERHOME)
    except OSError, exc:
        print _("The following error occurred: %s\n" % `exc`)
        sys.exit(1)
    try:
        f = file(main.PID_PATH, 'w')
        print >>f, os.getpid()
    except IOError, exc:
        print _("The following error occurred: %s\n" % `exc`)
        sys.exit(1)
    else:
        f.close() # ensure it's written NOW

    atexit.register(os.remove, main.PID_PATH)


def _redirect_to_logfile():

    """
    Redirects stdout and stderr to the given logfile and stdin to /dev/null.
    """

    try:
        out_log = file(LOGFILE, "w", 0)
    except IOError, exc:
        print _("The following error occurred: %s\n" % `exc`)
        sys.exit(1)
    else:
        sys.stderr = sys.stdout = SyncWriter(out_log)

    sys.stdin = file("/dev/null", "r")

    # dummy write
    print "Log messages of %s" % (LOGFILE,)
    sys.stdout.flush()


def _gdesklets_main():

    """ gdesklets main function to start """

    # prepare gdesklets (locale, signals, program_init)
    gtk.gdk.threads_init()

    # build our sockets, trayicon and start them
    Starter()

    # Set the default DBus mainloop
    DBusGMainLoop(set_as_default = True)

    # enter gtk's mainloop
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()


_detach_as_daemon()
_write_pid()
_redirect_to_logfile()
if (settings.check_for_updates_visible and settings.check_for_updates):
    __checker = UpdateChecker()
    gobject.timeout_add(__checker.TIMEOUT, __checker.check)
_gdesklets_main()
