#!/bin/sh

# 1. 基础系统与组件链接修正
sed -i 's|op.supes.top|dl.openwrt.ai|g' /etc/opkg/distfeeds.conf 2>/dev/null
[ -x /bin/bash ] && sed -i 's|/bin/ash|/bin/bash|g' /etc/passwd 2>/dev/null && ln -sf /bin/bash /bin/sh 2>/dev/null
[ -x /usr/bin/wget ] && [ ! -x /usr/bin/wget-ssl ] && ln -sf /usr/bin/wget /usr/bin/wget-ssl
sed -i -e '/profile.d/d' /lib/upgrade/keep.d/base-files \
       -e 's/git-.*-\(.*\)/git-\1/g' /usr/lib/lua/luci/version.lua 2>/dev/null

# 2. 版本与环境参数提取
version=$(uci -q get base_config.@status[0].version)
case "$version" in ''|*[!0-9]*) version=0 ;; esac

for ip in $(uci -q get network.lan.ipaddr); do
	case "$ip" in *.*) lan_ip="${ip%%/*}"; break ;; esac
done
lan_ip="${lan_ip:-10.0.0.1}"

[ -z "$(uci -q get system.@system[0].hostname)" ] && uci -q set system.@system[0].hostname='Kwrt'
[ "$(uci -q get dropbear.main._direct)" != "1" ] && uci -q delete dropbear.main.Interface
case "$(uci -q get uhttpd.main.index_page)" in *cgi-bin/luci*) ;; *) uci -q add_list uhttpd.main.index_page='cgi-bin/luci' ;; esac

proc=$(grep -c '^processor' /proc/cpuinfo 2>/dev/null)
[ "${proc:-0}" -gt 0 ] 2>/dev/null || proc=3
sed -i "s/^threads =.*/threads = $proc/" /etc/uwsgi/vassals/luci-webui.ini 2>/dev/null

# 3. 内存分级计算
mem=0
[ -r /proc/meminfo ] && read -r _ mem _ < /proc/meminfo
case "$mem" in ''|*[!0-9]*) mem=0 ;; esac

c=1024; nf=16384
[ "$mem" -ge 65536 ]   && { c=2048;  nf=32768; }
[ "$mem" -ge 131072 ]  && { c=4096;  nf=65536; }
[ "$mem" -ge 262144 ]  && { c=8192;  nf=65536; }
[ "$mem" -ge 524288 ]  && { c=10000; nf=131072; }
[ "$mem" -ge 1048576 ] && { c=10000; nf=262144; }

# 4. 首次开机参数统一批量预设
if [ "$version" -lt 1 ]; then
	uci -q batch <<-EOF
		set luci.main.lang='auto'
		set uhttpd.main.rfc1918_filter='0'
		set uhttpd.main.redirect_https='0'
		set uhttpd.main.script_timeout='120'
		set upnpd.config.enabled='1'
		set firewall.@defaults[0].flow_offloading='1'
		set firewall.@defaults[0].flow_offloading_hw='1'
		set fstab.@global[0].anon_mount='1'
		set network.globals.packet_steering='1'
		set nft-qos.default.limit_enable='0'
		set system.@system[0].zonename='Asia/Shanghai'
		set system.@system[0].timezone='CST-8'
		set system.@system[0].ttylogin='1'
		set system.@system[0].zram_size_mb='$((mem / 1024 / 3))'
		del system.ntp.server
		add_list system.ntp.server='ntp.aliyun.com'
		add_list system.ntp.server='0.openwrt.pool.ntp.org'
		set dhcp.@dnsmasq[0].port='53'
		set dhcp.@dnsmasq[0].dns_redirect='1'
		set dhcp.@dnsmasq[0].allservers='1'
		set dhcp.@dnsmasq[0].localservice='0'
		set dhcp.@dnsmasq[0].rebind_protection='0'
		set dhcp.@dnsmasq[0].rebind_localhost='1'
		del dhcp.@dnsmasq[0].noresolv
		set dhcp.@dnsmasq[0].cachesize='$c'
		set dhcp.@dnsmasq[0].dnsforwardmax='$c'
		set dhcp.@dnsmasq[0].min_ttl='3600'
		set dhcp.lan.force='1'
		set dhcp._ta=domain
		set dhcp._ta.name='time.android.com'
		set dhcp._ta.ip='203.107.6.88'
		set dhcp._ta.comments='time.android'
	EOF

	(echo root; echo root) | passwd root >/dev/null 2>&1
	[ -f /usr/share/rpcd/acl.d/luci-theme-vantage.json ] && uci -q set luci.main.mediaurlbase='/luci-static/vantage'
	grep -q 'log-facility' /etc/dnsmasq.conf 2>/dev/null || echo "log-facility=/dev/null" >> /etc/dnsmasq.conf

	mkdir -p /etc/sysctl.d
	printf "net.nf_conntrack_max=%s\nnet.core.rmem_max=%s\n" "$nf" "$nf" > /etc/sysctl.d/50-local.conf

	if command -v nginx >/dev/null 2>&1 && [ -z "$(uci -q get wizard.pw)" ]; then
		uci -q batch <<-EOF
			set wizard.pw=shortcuts
			set wizard.pw.shortcut='pw'
			set wizard.pw.to_url='http://${lan_ip}/cgi-bin/luci/admin/services/passwall'
			set wizard.pw.comments='passwall'
			set nginx._sc_pw=server
			set nginx._sc_pw.server_name='pw'
			add_list nginx._sc_pw.listen='80'
			add_list nginx._sc_pw.listen='443'
			set nginx._sc_pw.return='302 http://${lan_ip}/cgi-bin/luci/admin/services/passwall'
			set dhcp._sc_pw=domain
			set dhcp._sc_pw.name='pw'
			set dhcp._sc_pw.ip='${lan_ip}'
			set dhcp._sc_pw.comments='PassWall'
		EOF
	fi
	version=1
fi

if command -v nginx >/dev/null 2>&1; then
	[ -z "$(uci -q get nginx.default_server)" ] && uci -q batch <<-EOF
		set nginx.default_server=server
		set nginx.default_server.server_name='kwrt'
		add_list nginx.default_server.listen='80 default_server'
		add_list nginx.default_server.listen='[::]:80 default_server'
		add_list nginx.default_server.include='conf.d/*.locations'
		set nginx.default_server.access_log='off; # logd openwrt'
	EOF
	if [ -f /etc/nginx/conf.d/luci.locations ]; then
		grep -q 'uwsgi_read_timeout' /etc/nginx/conf.d/luci.locations || sed -i '/include uwsgi_params;/a\\t\tuwsgi_read_timeout 300s;' /etc/nginx/conf.d/luci.locations
		grep -q 'ubus_script_timeout' /etc/nginx/conf.d/luci.locations || sed -i '/ubus_parallel_req/a\        ubus_script_timeout 600;' /etc/nginx/conf.d/luci.locations
	fi

	if [ -f /etc/nginx/uci.conf.template ]; then
		sed -i -e 's/128M/3072M/' -e 's/2 1k/4 512k/' /etc/nginx/uci.conf.template
		grep -q 'client_body_buffer_size' /etc/nginx/uci.conf.template || sed -i '/large_client_header_buffers/a\\tclient_body_buffer_size 128K;' /etc/nginx/uci.conf.template
	fi
fi

# 6. uWSGI 超时与 FullCone 探测（兼容 fw3/fw4）
for ini in /etc/uwsgi/vassals/luci-*.ini; do
	[ -f "$ini" ] && ! grep -q 'cgi-timeout' "$ini" && echo "cgi-timeout = 500" >> "$ini"
done
sed -i 's/limit-as = 1000/limit-as = 5000/g' /etc/uwsgi/vassals/luci-webui.ini 2>/dev/null

modprobe xt_FULLCONENAT >/dev/null 2>&1 || modprobe nft_fullcone >/dev/null 2>&1 || {
	iptables -L -t nat 2>/dev/null | grep -q 'FULLCONENAT' || \
	nft list ruleset 2>/dev/null | grep -q 'fullcone' || \
	uci -q set firewall.@defaults[0].fullcone='0'
}

# 7. 更新版本状态、一次性提交所有 UCI 配置并安全退出
[ -f /etc/config/base_config ] && {
	uci -q get base_config.@status[0] >/dev/null || uci -q add base_config status >/dev/null
	uci -q set base_config.@status[0].version="$version"
}

uci -q commit
rm -rf /tmp/luci-*
exit 0
