#!/bin/sh
# netflow-rules — 从 UCI 读取自定义规则，注入 mihomo config.yaml
# 用法: netflow-rules           → 只生成 /tmp/netflow_custom_rules.yaml
#       netflow-rules inject    → 生成并注入到 config.yaml 中
#       netflow-rules reload    → 注入后通过 mihomo API 热重载

CONFIG="/etc/netflow/config.yaml"
CUSTOM_RULES="/tmp/netflow_custom_rules.yaml"
BAK="${CONFIG}.bak"

API_PORT=$(uci -q get netflow.config.api_port 2>/dev/null || echo "9091")
API_SECRET=$(uci -q get netflow.config.api_secret 2>/dev/null || echo "netflow_secret")

generate() {
	>"$CUSTOM_RULES"
	count=0
	for sec in $(uci -q show netflow 2>/dev/null | grep '^netflow\.@custom_rule\[' | sed 's/=.*//'); do
		t=$(uci -q get "${sec}.type" 2>/dev/null)
		v=$(uci -q get "${sec}.value" 2>/dev/null)
		p=$(uci -q get "${sec}.policy" 2>/dev/null)
		if [ -n "$t" ] && [ -n "$v" ] && [ -n "$p" ]; then
			echo "  - ${t},${v},${p}" >> "$CUSTOM_RULES"
			count=$((count + 1))
		fi
	done
	return $count
}

inject() {
	generate
	if [ $? -eq 0 ]; then
		logger -t netflow-rules "no custom rules defined, skipping"
		rm -f "$CUSTOM_RULES"
		return 0
	fi

	if [ ! -f "$CONFIG" ] || [ ! -s "$CONFIG" ]; then
		logger -t netflow-rules "config.yaml not found or empty, skip inject"
		return 0
	fi

	MATCH_LINE=$(grep -n -m1 'MATCH,' "$CONFIG" 2>/dev/null | cut -d: -f1)
	if [ -z "$MATCH_LINE" ]; then
		logger -t netflow-rules "no MATCH rule found in config.yaml, skip inject"
		return 0
	fi

	TMP_CONFIG="/tmp/netflow_config_patched.yaml"
	cp "$CONFIG" "$BAK"

	head -n $((MATCH_LINE - 1)) "$CONFIG" > "$TMP_CONFIG"
	cat "$CUSTOM_RULES" >> "$TMP_CONFIG"
	tail -n +${MATCH_LINE} "$CONFIG" >> "$TMP_CONFIG"

	if [ -s "$TMP_CONFIG" ]; then
		mv "$TMP_CONFIG" "$CONFIG"
		logger -t netflow-rules "custom rules injected into config.yaml"
	else
		logger -t netflow-rules "ERROR: patched config is empty, restoring backup"
		cp "$BAK" "$CONFIG"
	fi

	rm -f "$CUSTOM_RULES"
}

reload_mihomo() {
	if command -v curl >/dev/null 2>&1; then
		curl -s -X PUT \
			-H "Authorization: Bearer ${API_SECRET}" \
			-H "Content-Type: application/json" \
			-d "{\"path\":\"${CONFIG}\"}" \
			"http://127.0.0.1:${API_PORT}/configs" >/dev/null 2>&1
		ret=$?
	elif command -v wget >/dev/null 2>&1; then
		wget -qO- --method=PUT \
			--header="Authorization: Bearer ${API_SECRET}" \
			--header="Content-Type: application/json" \
			--body-data="{\"path\":\"${CONFIG}\"}" \
			"http://127.0.0.1:${API_PORT}/configs" >/dev/null 2>&1
		ret=$?
	else
		logger -t netflow-rules "curl/wget not found, cannot reload mihomo"
		return 1
	fi

	if [ $ret -eq 0 ]; then
		logger -t netflow-rules "mihomo config reloaded"
	else
		logger -t netflow-rules "mihomo reload failed (code=${ret})"
	fi
	return $ret
}

case "${1:-}" in
	inject)
		inject
		;;
	reload)
		inject
		reload_mihomo
		;;
	*)
		generate
		;;
esac
