#!/bin/sh
# E-IX 首次安装 / 首次启动执行一次（opkg 装包后或首次开机由 OpenWrt 自动运行并删除；
# install.sh 也会直接调用它）。幂等，可重复执行。
#
# 1. 建数据目录 /etc/eix 并锁权限（0700，内部文件 0600，root 所有）
# 2. 补齐缺失的 /etc/config/eix
# 3. 注册 fw4 include（放行 LAN -> TUN 转发；旁路由 masquerade 链的占位 include）
# 4. 立即应用 /etc/sysctl.d/99-eix.conf

DATA_DIR=/etc/eix
FW_INCLUDE=/etc/eix-firewall.nft
FW_BYPASS=/etc/eix-bypass.nft
SYSCTL_CONF=/etc/sysctl.d/99-eix.conf

# 1. 数据目录权限
mkdir -p "$DATA_DIR"
chown root:root "$DATA_DIR" 2>/dev/null
chmod 0700 "$DATA_DIR"
find "$DATA_DIR" -type d -exec chmod 0700 {} \; 2>/dev/null
find "$DATA_DIR" -type f -exec chmod 0600 {} \; 2>/dev/null
find "$DATA_DIR" -type f -exec chown root:root {} \; 2>/dev/null

# 2. 默认 UCI 配置
if [ ! -f /etc/config/eix ]; then
	cat > /etc/config/eix <<-EOF
		config eix 'main'
			option enabled '0'
			option mode 'rule'
			option tun_stack 'system'
			option node ''
			option tags '0'
			option dns_mode 'auto'
			option dns_hijack '1'
			option role 'router'
	EOF
fi
# 老配置缺字段时补默认值（不覆盖已有值）
[ -n "$(uci -q get eix.main)" ] || uci -q set eix.main=eix
[ -n "$(uci -q get eix.main.enabled)" ] || uci -q set eix.main.enabled='0'
[ -n "$(uci -q get eix.main.mode)" ] || uci -q set eix.main.mode='rule'
[ -n "$(uci -q get eix.main.tun_stack)" ] || uci -q set eix.main.tun_stack='system'
[ -n "$(uci -q get eix.main.tags)" ] || uci -q set eix.main.tags='0'
[ -n "$(uci -q get eix.main.dns_mode)" ] || uci -q set eix.main.dns_mode='auto'
[ -n "$(uci -q get eix.main.dns_hijack)" ] || uci -q set eix.main.dns_hijack='1'
[ -n "$(uci -q get eix.main.role)" ] || uci -q set eix.main.role='router'
uci -q commit eix

# 3. fw4 include（仅 firewall4 系统；fw3 由 init 脚本在启动时直接插 iptables 规则）
if command -v fw4 >/dev/null 2>&1 && [ -f "$FW_INCLUDE" ]; then
	if [ "$(uci -q get firewall.eix.path)" != "$FW_INCLUDE" ]; then
		uci -q batch <<-EOF
			delete firewall.eix
			set firewall.eix=include
			set firewall.eix.type='nftables'
			set firewall.eix.path='$FW_INCLUDE'
			set firewall.eix.position='chain-pre'
			set firewall.eix.chain='forward'
			commit firewall
		EOF
		# 防火墙可能尚未启动（首次开机）；能 reload 就 reload，失败无妨
		/etc/init.d/firewall reload >/dev/null 2>&1
	fi
	# 旁路由 masquerade 链：占位文件（只含注释），内容由 /etc/init.d/eix 按 UCI role 在启动时生成
	if [ ! -f "$FW_BYPASS" ]; then
		printf '%s
' "# E-IX：旁路由 masquerade（由 /etc/init.d/eix 按 UCI eix.main.role 自动生成，请勿手改）" "# role=router：无规则" > "$FW_BYPASS"
		chmod 0644 "$FW_BYPASS"
	fi
	if [ "$(uci -q get firewall.eix_bypass.path)" != "$FW_BYPASS" ]; then
		uci -q batch <<-EOF
			delete firewall.eix_bypass
			set firewall.eix_bypass=include
			set firewall.eix_bypass.type='nftables'
			set firewall.eix_bypass.path='$FW_BYPASS'
			set firewall.eix_bypass.position='table-post'
			commit firewall
		EOF
		/etc/init.d/firewall reload >/dev/null 2>&1
	fi
fi

# 4. sysctl 立即生效（重启后由 /etc/init.d/sysctl 自动加载 /etc/sysctl.d/*.conf）
if [ -f "$SYSCTL_CONF" ]; then
	sysctl -e -p "$SYSCTL_CONF" >/dev/null 2>&1
fi

exit 0
