#!/usr/bin/env bash

# USAGE:
# configure-firewall-post IDENTIFIER SSH_ARGS... < FIREWALL_RULES
#
# updates firewall-post using markers, forcibly re-running the firewall configurator
# the first arg must be the identifier for the firewall ruleset, and must match '^[0-9A-Za-z -]*$'
# firewall-post will be updated with markers like "GENERATED BY NetOps {IDENTIFIER} {BEGIN|END}"
# the remaining args must be the ssh connection options / user@host / etc
#
# notes on the (gnu) sed script:
# - the first address ($) matches end of file and runs commands to append the iptables commands (stdin) to lh
#   firewall-post with markers
# - execution of the (last) cycle will continue even if the first address is matched
# - the second address matches and deletes anything between and including the two markers (works on multiple pairs)
#   DANGER: this means that if JUST the first marker is matched then everything after it will be deleted (if the first
#   marker doesn't get matched at all it won't delete anything)
# - the single command for the second address `d` causes the cycle to stop execution
# - by default anything not matched gets included in the output
[ "$#" -ge 2 ] \
&& [ ! -z "$1" ] \
&& ( r='^[0-9A-Za-z -]*$' && [[ $1 =~ $r ]] ) \
&& identifier="$1" \
&& shift \
&& ssh "$@" 'mkdir -p /etc/config/scripts \
&& ( echo "# GENERATED BY NetOps '"$identifier"' BEGIN"; echo "# GENERATED BY NetOps '"$identifier"' END" ) | tee -a /etc/config/scripts/firewall-post > /dev/null \
&& sed -i -e '"'"'
    $ {
        a # GENERATED BY NetOps '"$identifier"' BEGIN
        a
        r /dev/stdin
        a
        a # GENERATED BY NetOps '"$identifier"' END
    }
    /^# GENERATED BY NetOps '"$identifier"' BEGIN$/,/^# GENERATED BY NetOps '"$identifier"' END$/d
'"'"' /etc/config/scripts/firewall-post \
&& ( c="$( command -v configurator_firewall )" || exit 0; "$c" --force ) \
&& grep -q -- "^# GENERATED BY NetOps '"$identifier"'" /etc/config/scripts/firewall-post'
