#!/bin/bash

set -eu

# This script opens HTTP port on 'start' without modifying the firewall dynamic config.
# On 'stop' it restores the policy configured in the firewall dynamic config.

get_http_port_policy() {
    nft -a list ruleset | grep "comment \"http\"" | sed -n "s/^.*80 \(\w\+\) comment .* handle \(\w\+\)/\1 \2/p"
}

set_http_port_policy() {
    local -r policy="${1}"
    local -r handle="${2}"
    
    nft replace rule inet lwr input handle "${handle}" tcp dport 80 "${policy}" comment \"http\"
}

apply_http_port_polcy() {
    local -r desired_policy="${1}"
    local actual_policy
    local handle
    read -r actual_policy handle <<< "$(get_http_port_policy)"
    if [ "${actual_policy}" != "${desired_policy}" ]; then
        echo "firewall-failsafe: Set HTTP policy to ${desired_policy}"
        set_http_port_policy "${desired_policy}" "${handle}"
    fi
}

get_configured_port_policy() {
    busctl get-property com.lightware.network.firewall \
        /com/lightware/network/firewall/services/http \
        com.lightware.network.firewall.DynamicService \
        Policy | cut -d' ' -f2 | tr -d '"'
}

main() {

    case "${1:?Missing argument: start|stop}" in
        start)
            apply_http_port_polcy "accept"
            ;;
        stop)
            configured_policy="$(get_configured_port_policy)"
            apply_http_port_polcy "${configured_policy}"
            ;;
        *)
            echo "Invalid argument: ${1}. Expected: start|stop."
            exit 1
            ;;
    esac
}

main "$@"