#!/usr/bin/env bash
# security/firewall -- show rules, allow a port, warn before anything unsafe
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t mod_sec_firewall)"

if ! nv_have ufw; then
    ui_err "$(t fw_not_installed)"
    exit 1
fi

ui_kv "$(t fw_state)" "$(fw_status)"
ui_section "$(t fw_rules)"
ufw status numbered 2>/dev/null | sed -n '4,$p' | sed 's/^/  /'
ui_blank

printf '  %s (0 = %s): ' "$(t fw_prompt_allow)" "$(t menu_back)"
read -r port || exit 130
case $port in
    ''|0) exit 0 ;;
    *[!0-9]*) ui_err "$(t ui_invalid_number)"; exit 2 ;;
esac
nv_valid_port "$port" || { ui_err "$(t fw_bad_port)"; exit 2; }

if [ "$port" = "22" ] && ! ui_confirm "$(t fw_confirm_ssh)" n; then
    exit 0
fi

fw_allow "$port" tcp
nv_trace firewall "allow $port/tcp"
ui_ok "$(t fw_allowed "$port")"
exit 0
