#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +--------------------------------------------------------------------------+
# | OpenFW UTM Community                                                     |
# +--------------------------------------------------------------------------+

import subprocess
import sys


def run_iptables(args):
    try:
        try:
            from subprocess import DEVNULL
        except ImportError:
            import os
            DEVNULL = open(os.devnull, 'wb')

        subprocess.run(["iptables"] + args, stdout=DEVNULL, stderr=DEVNULL, check=False)
    except AttributeError:
        import os
        try:
            with open(os.devnull, 'wb') as devnull:
                subprocess.call(["iptables"] + args, stdout=devnull, stderr=devnull)
        except Exception:
            pass
    except Exception:
        pass


def main():
    chain = "ALLOW"

    run_iptables(["-D", chain, "-i", "lo", "-j", "RETURN"])
    run_iptables(["-D", chain, "-j", "NFQUEUE", "--queue-balance", "100:101", "--queue-bypass"])
    run_iptables(["-D", chain, "-j", "ACCEPT"])

    try:
        if hasattr(subprocess, "run"):
            subprocess.run(["iptables", "-A", chain, "-i", "lo", "-j", "RETURN"], check=True)
            subprocess.run([
                "iptables", "-A", chain, "-j", "NFQUEUE", 
                "--queue-balance", "100:101", "--queue-bypass"
            ], check=True)
        else:
            subprocess.check_call(["iptables", "-A", chain, "-i", "lo", "-j", "RETURN"])
            subprocess.check_call([
                "iptables", "-A", chain, "-j", "NFQUEUE", 
                "--queue-balance", "100:101", "--queue-bypass"
            ])

    except Exception:
        sys.exit(1)


if __name__ == "__main__":
    main()