#!/bin/sh -e
#
# 2013 Nico Schottelius (nico-cdist at schottelius.org)
# 2020 Matthias Stecher (matthiasstecher at gmx.de)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#
#

base_dir=/etc/iptables.d

name="$__object_id"
state="$(cat "$__object/parameter/state")"

if [ -f "$__object/parameter/v4" ]; then
    only_v4="yes"
    # $specific_dir is $base_dir
fi
if [ -f "$__object/parameter/v6" ]; then
    only_v6="yes"
    specific_dir="$base_dir/v6"
fi
# If rules should be set for both protocols
if { [ "$only_v4" = "yes" ] && [ "$only_v6" = "yes" ]; } ||
    [ -f "$__object/parameter/all" ]; then

    # all to a specific directory
    specific_dir="$base_dir/all"
fi

# set rule directory based on if it's the base or subdirectory
rule_dir="${specific_dir:-$base_dir}"

################################################################################
# Basic setup
#

__directory "$base_dir" --state present

# sub-directory if required
if [ "$specific_dir" ]; then
    require="__directory/$base_dir" __directory "$specific_dir" --state present
fi

# Have apply do the real job
require="$__object_name" __iptables_apply

################################################################################
# The rule
#

for dir in "$base_dir" "$base_dir/v6" "$base_dir/all"; do
    # defaults to absent except the directory that should contain the file
    if [ "$rule_dir" = "$dir" ]; then
        curr_state="$state"
    else
        curr_state="absent"
    fi

    require="__directory/$rule_dir" __file "$dir/$name" \
        --source "$__object/parameter/rule" \
        --state "$curr_state"
done
