#!/bin/sh

VARS_CONF="/etc/bird/vars.conf"
NEXTTRACE="/etc/bird-lg/nexttrace"

# 1. 提取目标 IP (URL 中的 q 参数传过来的最后一个参数)
TARGET=$(echo "$@" | awk '{print $NF}')

# 2. 预设必须要带的 nexttrace 参数
# 这样即使 bird-lgproxy.yaml 里没写全，这里也会兜底
FIXED_ARGS="-C -n -M -q 1"

# --- 内部函数：从 vars.conf 提取定义的值 ---
get_var() {
    grep -E "define[[:space:]]+$1" "$VARS_CONF" | awk -F'=' '{print $2}' | tr -d ' ;"' | xargs
}

# --- 3. 根据目标 IP 段选择 Source IP ---
SRC_IP=""

if echo "$TARGET" | grep -q ':'; then
    # IPv6 逻辑
    if echo "$TARGET" | grep -qiE '^fd'; then
        SRC_IP=$(get_var "DN42_V6_kernel")
    else
        SRC_IP=$(get_var "LOCAL_V6_kernel")
    fi
else
    # IPv4 逻辑
    if echo "$TARGET" | grep -qE '^(172\.(2[0-3]|1[6-9]))'; then
        SRC_IP=$(get_var "DN42_V4_kernel")
    elif echo "$TARGET" | grep -qE '^10\.'; then
        SRC_IP=$(get_var "UNET_V4_kernel")
    else
        SRC_IP=$(get_var "LOCAL_V4_kernel")
    fi
fi

# --- 4. 组合并执行 ---
# 确保如果没读到变量，就不传 -s，避免 nexttrace 报错
if [ -n "$SRC_IP" ]; then
    # 使用 exec 替换当前进程，效率最高
    exec "$NEXTTRACE" $FIXED_ARGS -s "$SRC_IP" "$TARGET"
else
    exec "$NEXTTRACE" $FIXED_ARGS "$TARGET"
fi