#!/usr/bin/env python
# -*- coding: utf-8 -*-

###########################################################################
# Launch the epoptes UI.
#
# Copyright (C) 2011 Alkis Georgopoulos <alkisg@gmail.com>
#
# 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 3 of the License, 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 FINESS 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, see <http://www.gnu.org/licenses/>.
#
# On Debian GNU/Linux systems, the complete text of the GNU General
# Public License can be found in `/usr/share/common-licenses/GPL".
###########################################################################

import os
import os.path
import sys
import gtk
import epoptes

# cd to the epoptes directory, so that all paths are relative
os.chdir('/usr/share/epoptes')

# Do these potentially expensive imports now we know the environment is sane
from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp

from epoptes.daemon import uiconnection
from epoptes.ui import gui
from epoptes.common import config

# Check that the user is a member of the epoptes SOCKET_GROUP
import grp
try:
    is_member = os.environ['USER'] in [config.system['SOCKET_GROUP']] + \
        grp.getgrnam(config.system['SOCKET_GROUP']).gr_mem
except:
    is_member = False
if not is_member:
    msg = _("User %s must be a member of group %s to run epoptes.") % \
        (os.environ['USER'], config.system['SOCKET_GROUP'])
    dlg = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK,
        message_format=msg)
    dlg.set_title(_('Error'))
    dlg.run()
    dlg.destroy()
    sys.exit(msg)

epoptesGui = gui.EpoptesGui()

def connectionFailed(failure):
    print "Connection with epoptes failed:"
    print failure.getErrorMessage()
    reactor.stop()

d = ClientCreator(reactor, epoptes.daemon.uiconnection.Daemon, epoptesGui).connectUNIX(config.system['DIR'] + "/epoptes.socket")
d.addErrback(connectionFailed)

reactor.run()
