#!/usr/bin/python -OO
# -*- coding: utf-8 -*-
# vim: ts=4 
###
#
# Listen is the legal property of mehdi abaakouk <theli48@gmail.com>
# Copyright (c) 2006 Mehdi Abaakouk
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
###

import os
import sys
import locale
import gettext
gettext.install("listen", unicode=1)
import traceback 
import errno

from option_parser import ListenOptionParser

if "--help" in sys.argv or "-h" in sys.argv:
    ListenOptionParser()
    sys.exit(0)

import gobject
gobject.threads_init()

import pygtk
pygtk.require("2.0")

try:import gnome.ui
except ImportError: pass
else:
    gnome.ui.authentication_manager_init()


import gtk
if gtk.pygtk_version < (2,6) or gtk.gtk_version < (2, 6):
    raise ImportError,"Need GTK > 2.6.0"
gtk.gdk.threads_init()

import pygst
pygst.require("0.10")

import gst
if gst.pygst_version < (0, 10, 1):
    raise ImportError,"Need Gstreamer >= 0.10.1"

import mutagen 
if mutagen.version < (1, 8):
    raise ImportError,"Need mutagen >= 1.8"

# Add lib correct path
current_path = os.path.realpath(__file__)
basedir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(basedir, "listen.py")):
    if os.path.exists(os.path.join(os.getcwd(), "listen.py")):
        basedir = os.getcwd()
#sys.path.insert(0, basedir)
#os.chdir(basedir)

from const import APPNAME, VERSION
from stock import stock_init
from vfs import makedirs

from updater import Updater

from xdg_support import get_xdg_cache_file

PIDFILE = get_xdg_cache_file("listen.pid")

class ListenApp:
    listen_instance = None  
    splash=None  

    def __init__(self):
        #sys.excepthook = self.__cb_exception    
        
        self.option = ListenOptionParser()
        
        if not self.listen_is_alive():
            self.option.run_preload()
            
            stock_init()
            from config import config
            config.load()

            try:import gnome
            except ImportError: pass
            else:

                self.program = gnome.init(
                    APPNAME, VERSION,
                    gnome.libgnome_module_info_get(), sys.argv, []
                )

                client = gnome.ui.master_client()
                client.set_restart_style(gnome.ui.RESTART_IF_RUNNING)
                command = os.path.normpath(os.path.join(os.getcwd(), sys.argv[0]))
                try: client.set_restart_command([command] + sys.argv[1:])
                except TypeError:
                    # Fedora systems have a broken gnome-python wrapper for this function.
                    # http://www.sacredchao.net/quodlibet/ticket/591
                    # http://trac.gajim.org/ticket/929
                    client.set_restart_command(len(sys.argv), [command] + sys.argv[1:])
                client.connect('die', gtk.main_quit)
            

            
            from widget.listen import Listen
            self.listen_instance = Listen()
            self.listen_instance.connect("ready",self.on_ready_cb)
           
            # Create pid file
            f = open(PIDFILE, 'w')
            f.write(str(os.getpid()))
            f.close()
            del f

            gtk.main()
            # Delete PID
            if os.path.exists(PIDFILE):
                os.remove(PIDFILE)

            print "Listen existed"

        else:
            self.option.run_load()
        
        sys.exit(0)

    def listen_is_alive(self):
        try:
            pf = open(PIDFILE)
        except:
            # probably file not found
            return False

        try:
            pid = int(pf.read().strip())
            pf.close()
        except:
            traceback.print_exc()
            # PID file exists, but something happened trying to read PID
            # Could be 0.10 style empty PID file, so assume Listen is running
            return True

        try:
            if not os.path.exists('/proc'):
                print "missing /proc"
                return True # no /proc, assume Listen is running

            try:
                f = open('/proc/%d/cmdline'% pid) 
            except IOError, e:
                if e.errno == errno.ENOENT:
                    return False # file/pid does not exist
                raise 

            n = f.read().lower()
            f.close()
            if n.find('listen') < 0:
                return False
            return True # Running Listen found at pid
        except:
            traceback.print_exc()

        # If we are here, pidfile exists, but some unexpected error occured.
        # Assume Listen is running.
        return True


    def on_ready_cb(self,listen):
        from library import ListenDB
        ListenDB.load()
        self.option.run_load( self.listen_instance.dbus_service )
        from plugins.generic import GenericManager
        GenericManager()
        from player import Player
        Player.load()
        from vfs import FileMonitor
        FileMonitor.start()


if __name__ == "__main__":
    Updater()
    ListenApp()
    import atexit
    atexit.register(gtk.main_quit)
    signal(SIGINT, lambda signum, stack_frame: exit(1))
            
