#!/bin/sh
# 接口起来(开机 WAN / PPPoE 拨上、换网)时:
#   内核在跑 → 后台拉一次订阅(开机时 WAN 没起来拉失败的,不用等 30 分钟的定时任务);
#   内核不在 → 撤掉上次留下的防火墙规则(断电没来得及 stop,fw4 开机把旧 include 又加载了;
#             它和 20-firewall 在同一个 ifup 事件里跑,我们排在后面)。启动交给 /etc/init.d/mihomo(S99)。
# hotplug 脚本是被 . 进来跑的,不要 exit。
if [ "$ACTION" = "ifup" ] && [ "$INTERFACE" != "loopback" ]; then
	if [ "$(uci -q get mihomo.config.enabled)" = "1" ]; then
		if pgrep -f "^/usr/bin/mihomo -d " >/dev/null 2>&1; then
			# 同一次拨号可能连着来几个 ifup(wan / wan6),60 秒内只拉一次
			_m_stamp=/var/run/mihomo/.ifup
			_m_now=$(date +%s)
			_m_last=$(cat "$_m_stamp" 2>/dev/null)
			if [ $((_m_now - ${_m_last:-0})) -ge 60 ]; then
				mkdir -p /var/run/mihomo && echo "$_m_now" > "$_m_stamp"
				( /etc/init.d/mihomo bgupdate ) </dev/null >/dev/null 2>&1 &
			fi
		elif [ ! -f /var/run/mihomo/stopped ]; then
			rm -f /usr/share/nftables.d/ruleset-post/mihomo.nft
			nft delete table inet mihomo 2>/dev/null
		fi
	fi
fi
