#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3


from winswitch.util.process_util import exec_nopipe
from winswitch.util.simple_logger import Logger

firewall_util = None
def get_firewall_util(config):
	global firewall_util
	if firewall_util is None:
		firewall_util = FirewallUtil(config)
	return firewall_util


class	FirewallUtil:
	def	__init__(self, config):
		Logger(self, log_colour=Logger.CYAN)
		self.config = config
		self.disabled_warning = False

	def add(self, host, port):
		self.call_script(["ADD", host, str(port)])

	def allow(self, from_ip, host, port):
		self.call_script(["ALLOW", from_ip, host, str(port)])

	def remove(self, from_ip, host, port):
		self.call_script(["REMOVE", from_ip, host, str(port)])

	def call_script(self, params):
		script = self.config.firewall_script
		self.sdebug("firewall_script=%s" % script, params)
		if not self.config.firewall_enabled:
			if not self.disabled_warning:
				self.slog("firewall script disabled", params)
				self.disabled_warning = True
			return
		if not script:
			return
		params.insert(0, script)
		exec_nopipe(params, wait=True)
