#!/bin/bash
set -eux

RULES_SCRIPT=/var/opt/undercloud-stack/masquerade

. $RULES_SCRIPT

iptables-save > /etc/sysconfig/iptables


# We are specifically running the following commands after the
# iptables rules to ensure the persisted file does not contain any
# ephemeral neutron rules. Neutron assumes the iptables rules are not
# persisted so it may cause an issue if the rule is loaded on boot
# (or via iptables restart). If an operator needs to reload iptables
# for any reason, they may need to manually reload the appropriate
# neutron agent to restore these iptables rules.
# https://bugzilla.redhat.com/show_bug.cgi?id=1541528
if /bin/test -f /etc/sysconfig/iptables && /bin/grep -q neutron- /etc/sysconfig/iptables
then
    /bin/sed -i /neutron-/d /etc/sysconfig/iptables
fi

if /bin/test -f /etc/sysconfig/ip6tables && /bin/grep -q neutron- /etc/sysconfig/ip6tables
then
    /bin/sed -i /neutron-/d /etc/sysconfig/ip6tables
fi


# Do not persist ephemeral firewall rules managed by ironic-inspector
# pxe_filter 'iptables' driver.
# https://bugs.launchpad.net/tripleo/+bug/1765700
if /bin/test -f /etc/sysconfig/iptables && /bin/grep -v "\-m comment \--comment" /etc/sysconfig/iptables | /bin/grep -q ironic-inspector
then
    /bin/sed -i "/-m comment --comment.*ironic-inspector/p;/ironic-inspector/d" /etc/sysconfig/iptables
fi

if /bin/test -f /etc/sysconfig/ip6tables && /bin/grep -v "\-m comment \--comment" /etc/sysconfig/ip6tables | /bin/grep -q ironic-inspector
then
    /bin/sed -i "/-m comment --comment.*ironic-inspector/p;/ironic-inspector/d" /etc/sysconfig/ip6tables
fi
