#!/usr/bin/python

import logging
import warnings

warnings.filterwarnings('ignore', category=DeprecationWarning)

from ppacommon.network import ip6tables
from ppacommon.network import iptables
from ppacommon.network import getHostIPs
from ppacommon import yum
from ppacommon import utils

PG_CHAIN = 'Postgres'
INPUT_CHAIN = 'INPUT'
IPTABLES_V6_NAME = 'ip6tables'
IPTABLES_V6_YUM = 'iptables-ipv6'

logger = logging.getLogger('ppa')
logger.setLevel(logging.DEBUG)
cl = logging.StreamHandler()
cl.setLevel(logging.DEBUG)
logger.addHandler(cl)


def configureIptables(ips, iptLib):
    lineNumber = iptLib.getTargetLineNumberInChain(INPUT_CHAIN, PG_CHAIN)
    if lineNumber > 0:
        iptLib.delRule(INPUT_CHAIN, lineNumber)
        iptLib.delChain(PG_CHAIN, True)

    iptLib.addChain(PG_CHAIN)
    iptLib.insertRule(INPUT_CHAIN, 1, '-p tcp --dport 5432 -j %s' % PG_CHAIN)

    for ip in ips:
        iptLib.addRule(PG_CHAIN, '-p tcp -s %s -j ACCEPT' % ip)

    iptLib.addRule(PG_CHAIN, '-j DROP')
    iptLib.save()

hostIPs = getHostIPs()
hostIPv4s = set([x['ip'] for x in hostIPs if x['type'] == 'ipv4'])
hostIPv6s = set([x['ip'] for x in hostIPs if x['type'] == 'ipv6'])

configureIptables(hostIPv4s, iptables)

if len(hostIPv6s) > 1:
    if  utils.which(IPTABLES_V6_NAME) is None:
        yum.install([IPTABLES_V6_YUM, ])

    configureIptables(hostIPv6s, ip6tables)
