#!/usr/local/bin/python3

"""
    Copyright (c) 2021 Ad Schellevis <ad@opnsense.org>
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

"""
import os
import subprocess
from configparser import ConfigParser


if __name__ == '__main__':
    all_tables = dict()
    updater_conf = '/usr/local/etc/ipfw_rule_tables.conf'
    if os.path.exists(updater_conf):
        cnf = ConfigParser()
        cnf.read(updater_conf)
        for section in cnf.sections():
            if cnf.has_option(section, 'table_name') and cnf.has_option(section, 'table_content'):
                all_tables[cnf.get(section, 'table_name')] = cnf.get(section, 'table_content').split(',')

    ipfw_list_cmd = ['/sbin/ipfw', 'table', 'all', 'list']
    for line in subprocess.run(ipfw_list_cmd, capture_output=True, text=True).stdout.split('\n'):
        if line.startswith('---'):
            table_name = line.split('(')[1].split(')')[0]
            if table_name.startswith('__rule__') and table_name not in all_tables:
                subprocess.run(['/sbin/ipfw', 'table', table_name, 'destroy'], capture_output=True)

    for table_name in all_tables:
        # XXX: a full diff of the current table contents might be better, but for shaping purposes we likely won't
        #      notice the glitch
        subprocess.run(['/sbin/ipfw', 'table', table_name, 'flush'], capture_output=True)
        for address in all_tables[table_name]:
            subprocess.run(['/sbin/ipfw', 'table', table_name, 'add', address], capture_output=True)
