# Gufw 10.10.1 - http://gufw.tuxfamily.org
# Copyright (C) 2008-2010 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 time
import commands


class GufwLog:
    """Record and return Gufw Log"""
    def __init__(self):
        self.logging = self.get_gufw_logging()
    
    def get_gufw_logging(self):
        cmd = commands.getstatusoutput("grep log=enable /etc/gufw/gufw.cfg")
        if cmd[1].find("enable") != -1:
            return "enable"
        else:
            return "disable"
    
    def add_log(self, command):
        """Add a command to Gufw Log"""
        if self.logging == "enable":
            # Add log to Gufw log file
            msg = "[" + time.strftime('%x %X') + "] " + command
            cmd = "echo '&' >> /var/log/gufw_log.txt".replace("&", msg)
            commands.getstatusoutput(cmd)
            # Add log to Gufw server script log
            cmd = "echo '&' >> /var/log/gufw_log_server.txt".replace("&", command)
            commands.getstatusoutput(cmd)
        
    def get_log(self):
        """Return complete Gufw Log for local & server script"""
        cmd_local  = commands.getstatusoutput("cat /var/log/gufw_log.txt")
        if cmd_local[0] != 0:
            return "", ""
        cmd_server = commands.getstatusoutput("cat /var/log/gufw_log_server.txt")
        return cmd_local[1], cmd_server[1]
    
    def remove_log(self):
        """Remove complete Gufw Log"""
        commands.getstatusoutput("rm /var/log/gufw_log.txt && rm /var/log/gufw_log_server.txt")
    
    def get_logging(self):
        """Return the actual Gufw Log Status [enable|disable]"""
        return self.logging
        
    def set_logging(self, logging):
        """Set the actual Gufw Log Status [enable|disable]"""
        if logging == "disable":
            commands.getstatusoutput("sed -i 's/log=enable/log=disable/' /etc/gufw/gufw.cfg")
            self.logging = "disable"
        else:
            commands.getstatusoutput("sed -i 's/log=disable/log=enable/' /etc/gufw/gufw.cfg")
            self.logging = "enable"

    
