# Gufw 10.10.1 - http://gufw.tuxfamily.org
# Copyright (C) 2008-2010 Raul Soriano & Marcos Alvarez Costales <marcos@ubuntu-ast.org>
#
# Gufw 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.
# 
# Gufw 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 Gufw; if not, see http://www.gnu.org/licenses for more
# information.

import gtk
import os
import os.path
import commands


class Check:
    """Check if gufw is running as root application"""
    def __init__(self):
        self.is_root()
        self.exist_cfg_file()
    
    def is_root(self):
        if os.geteuid() != 0:
            dlg = gtk.MessageDialog(None, buttons=gtk.BUTTONS_CLOSE, message_format=("Run Gufw as root!"))
            dlg.run()
            dlg.destroy()
            exit(0)
    
    def exist_cfg_file(self):
        if not os.path.isfile("/etc/gufw/gufw.cfg"):
            commands.getstatusoutput("mkdir /etc/gufw")
            commands.getstatusoutput("echo 'log=enable' > /etc/gufw/gufw.cfg")
            commands.getstatusoutput("echo 'sizewin=336x334' >> /etc/gufw/gufw.cfg")
            commands.getstatusoutput("echo 'report=disable' >> /etc/gufw/gufw.cfg")

class Instance:
    """This class manages application instances"""
    def __init__(self):
        self.pid_file = "/tmp/gufw.pid"
        self.check()
        self.start_application()

    # Check wether the app is running
    def check(self):
        # Check wether the pid file exists
        if not os.path.isfile(self.pid_file):
            return

        # Read the pid from file
        pid = 0
        try:
            file = open(self.pid_file, 'rt')
            data = file.read()
            file.close()
            pid = int(data)
        except:
            pass
        
        # Check wether the proccess specified exists
        if 0 == pid:
            return
        try:
            os.kill(pid, 0)  # exception if the pid is invalid
        except:
            return
        
        exit(0)

    # Called when there is no running instances, storing the new pid
    def start_application(self):
        file = open(self.pid_file, 'wt')
        file.write( str(os.getpid()))
        file.close()

    # Removing the existing pid file
    def exit_application(self):
    # Close WindowsExitApplication(self):
        try:
            os.remove(self.pid_file)
        except:
            pass
