#!/bin/sh
# 兼容门面（compatibility facade）
# 宿主内核仅 legacy netfilter（ip_tables / xt_*），无 nf_tables；guest 自带的 fw4/nft
# 防火墙栈在本环境整体空转（nft 命令无法执行）。许多插件用 `command -v fw4` 判定防火墙
# 后端：有 fw4 就走 nft 规则，没有就走 iptables 规则。
#
# 默认（fw3，兼容模式）：系统防火墙用 fw3/iptables（/etc/init.d/firewall.fw3），
# 并隐藏 /sbin/fw4——这类插件自动改走 iptables-legacy 路径（经 uClibc 兼容层驱动 iKuai
# 内核 netfilter），透明代理（TPROXY/REDIRECT）即可生效。
# 实验（fw4）：恢复原生 nftables 栈（/sbin/fw4 与 /etc/init.d/firewall.fw4）。
# 选择来源：环境变量 FIREWALL_STACK（宿主 manager 注入），回退 /etc/compat-firewall-stack。
# 尽力而为：任何失败都不影响容器启动，始终退出 0。
stack="${FIREWALL_STACK:-}"
[ -n "$stack" ] || stack="$(cat /etc/compat-firewall-stack 2>/dev/null || echo fw3)"

# 保留一份原生 fw4 init 供实验模式切换（首跑时备份）。
if [ ! -e /etc/init.d/firewall.fw4 ] && [ -e /etc/init.d/firewall ]; then
	cp /etc/init.d/firewall /etc/init.d/firewall.fw4 2>/dev/null
fi

if [ "$stack" = "fw4" ]; then
	# 实验：恢复 fw4 二进制与 init。
	[ -e /sbin/.fw4.hidden ] && mv /sbin/.fw4.hidden /sbin/fw4 2>/dev/null
	[ -e /etc/init.d/firewall.fw4 ] && cp /etc/init.d/firewall.fw4 /etc/init.d/firewall 2>/dev/null
else
	# 兼容：启用 fw3 init，隐藏 fw4。
	[ -e /etc/init.d/firewall.fw3 ] && cp /etc/init.d/firewall.fw3 /etc/init.d/firewall 2>/dev/null
	if [ -e /sbin/fw4 ] && [ ! -e /sbin/.fw4.hidden ]; then
		mv /sbin/fw4 /sbin/.fw4.hidden 2>/dev/null
	fi
fi
chmod 0755 /etc/init.d/firewall 2>/dev/null
[ -x /etc/init.d/firewall ] && /etc/init.d/firewall enabled 2>/dev/null
exit 0
